From e44275b2c41d901d7cadd98253a884068683ce9b Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 13 Jan 2017 08:14:36 -0800 Subject: [PATCH 01/72] del: Lint --- del/index.d.ts | 17 +++++------------ del/tslint.json | 1 + 2 files changed, 6 insertions(+), 12 deletions(-) create mode 100644 del/tslint.json diff --git a/del/index.d.ts b/del/index.d.ts index fd37a8ff91..50634e39eb 100644 --- a/del/index.d.ts +++ b/del/index.d.ts @@ -1,21 +1,14 @@ -// Type definitions for del v2.2.0 +// Type definitions for del 2.2 // Project: https://github.com/sindresorhus/del // Definitions by: Asana , Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import glob = require("glob"); -declare function Del(pattern: string): Promise; -declare function Del(pattern: string, options: Del.Options): Promise; +declare function del(patterns: string | string[], options?: del.Options): Promise; -declare function Del(patterns: string[]): Promise; -declare function Del(patterns: string[], options: Del.Options): Promise; - -declare namespace Del { - function sync(pattern: string, options?: Options): string[]; - function sync(patterns: string[], options?: Options): string[]; +declare namespace del { + function sync(patterns: string | string[], options?: Options): string[]; interface Options extends glob.IOptions { force?: boolean; @@ -23,4 +16,4 @@ declare namespace Del { } } -export = Del; +export = del; diff --git a/del/tslint.json b/del/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/del/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file From cb354dc6572ec81b3826360cc83b8ffb8e79423f Mon Sep 17 00:00:00 2001 From: Aluan Haddad Date: Fri, 13 Jan 2017 12:02:57 -0500 Subject: [PATCH 02/72] Fix "Discover JCB" -> "Discover" | "JCB", refine StripeStatic.cardType Fixed bug previously introduced due to misread documentation. Refined the return type of `StripeStatic.cardType`, `string` => `StripeCardDataBrand`. --- stripe/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stripe/index.d.ts b/stripe/index.d.ts index fdfa1db96e..a7d887c747 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -11,7 +11,7 @@ interface StripeStatic { validateCardNumber(cardNumber: string): boolean; validateExpiry(month: string, year: string): boolean; validateCVC(cardCVC: string): boolean; - cardType(cardNumber: string): string; + cardType(cardNumber: string): StripeCardDataBrand; getToken(token: string, responseHandler: (status: number, response: StripeTokenResponse) => void): void; card: StripeCardData; createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; @@ -51,7 +51,7 @@ interface StripeError { param?: string; } -type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover JCB' | 'Diners Club' | 'Unknown'; +type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; interface StripeCardData { object: string; From 04a511fce4875ecac929a57bc1d6c534f6a6e1c0 Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Sat, 14 Jan 2017 22:23:16 -0800 Subject: [PATCH 03/72] Added lolex 1.5.2 types Previous types didn't account for browser or node differences, and didn't include more advanced functions like `runAll` in the `Clock` spec. --- lolex/index.d.ts | 187 +++++++++++++++++++++++++++++++++++++++---- lolex/lolex-tests.ts | 166 ++++++++++++++------------------------ 2 files changed, 235 insertions(+), 118 deletions(-) diff --git a/lolex/index.d.ts b/lolex/index.d.ts index 544fb88fb6..7a03b3fd2c 100644 --- a/lolex/index.d.ts +++ b/lolex/index.d.ts @@ -1,28 +1,187 @@ // Type definitions for lolex 1.5.1 // Project: https://github.com/sinonjs/lolex -// Definitions by: Wim Looman +// Definitions by: Wim Looman , Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Timer object used in node. + */ +export type NodeTimer = { + /** + * Stub method call. Does nothing. + */ + ref(): void; -export interface Clock { + /** + * Stub method call. Does nothing. + */ + unref(): void; +} + +/** + * Timer identifier for clock scheduling. + */ +export type TimerId = number | NodeTimer; + +/** + * Lolex clock for a browser environment. + */ +type BrowserClock = IClock; + +/** + * Lolex clock for a Node environment. + */ +type NodeClock = IClock & { + /** + * Mimicks process.hrtime(). + * + * @param prevTime Previous system time to calculate time elapsed. + * @returns High resolution real time as [seconds, nanoseconds]. + */ + hrtime(prevTime?: [number, number]): [number, number]; +} + +/** + * Clock object created by lolex. + */ +type Clock = BrowserClock | NodeClock; + +/** + * Names of clock methods that may be faked by install. + */ +type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date"; + +/** + * Controls the flow of time. + */ +export interface IClock { + /** + * Current clock time. + */ now: number; - setTimeout(callback: () => any, timeout: number): number; - setInterval(callback: () => any, timeout: number): number; - setImmediate(callback: () => any): number; + /** + * Implements the Date object but using this clock to provide the correct time. + */ + Date: typeof Date; - clearTimeout(id: number): void; - clearInterval(id: number): void; - clearImmediate(id: number): void; + /** + * Schedules a callback to be fired once timeout milliseconds have ticked by. + * + * @param callback Callback to be fired. + * @param timeout How many ticks to wait to run the callback. + * @returns Time identifier for cancellation. + */ + setTimeout(callback: () => any, timeout: number): TTimerId; - setSystemTime(now: number): void; - setSystemTime(date: Date): void; + /** + * Clears a timer, as long as it was created using setTimeout. + * + * @param id Timer ID or object. + */ + clearTimeout(id: TTimerId): void; - tick(ms: number): void; + /** + * Schedules a callback to be fired every time timeout milliseconds have ticked by. + * + * @param callback Callback to be fired. + * @param timeout How many ticks to wait between callbacks. + * @returns Time identifier for cancellation. + */ + setInterval(callback: () => any, timeout: number): TTimerId; + + /** + * Clears a timer, as long as it was created using setInterval. + * + * @param id Timer ID or object. + */ + clearInterval(id: TTimerId): void; + + /** + * Schedules the callback to be fired once 0 milliseconds have ticked by. + * + * @param callback Callback to be fired. + * @remarks You'll still have to call clock.tick() for the callback to fire. + * @remarks If called during a tick the callback won't fire until 1 millisecond has ticked by. + */ + setImmediate(callback: () => any): TTimerId; + + /** + * Clears a timer, as long as it was created using setImmediate. + * + * @param id Timer ID or object. + */ + clearImmediate(id: TTimerId): void; + + /** + * Advances the clock to the the moment of the first scheduled timer, firing it. + */ + next(): void; + + /** + * Advance the clock, firing callbacks if necessary. + * + * @param time How many ticks to advance by. + */ + tick(time: number | string): void; + + /** + * Runs all pending timers until there are none remaining. + * + * @remarks If new timers are added while it is executing they will be run as well. + */ + runAll(): void; + + /** + * Takes note of the last scheduled timer when it is run, and advances the clock to + * that time firing callbacks as necessary. + */ + runToLast(): void; + + /** + * Simulates a user changing the system clock. + * + * @param now New system time. + * @remarks This affects the current time but it does not in itself cause timers to fire. + */ + setSystemTime(now?: number | Date): void; + + /** + * Restores the original methods on the context that was passed to lolex.install, + * or the native timers if no context was given. + */ uninstall(): void; } -export declare function createClock(now?: number): Clock; +/** + * Creates a clock. + * + * @param now Current time for the clock. + * @param loopLimit Maximum number of timers that will be run when calling runAll() + * before assuming that we have an infinite loop and throwing an error + * (by default, 1000). + * @type TClock Type of clock to create. + * @remarks The default epoch is 0. + */ +export declare function createClock(now?: number | Date, loopLimit?: number): TClock; -export declare function install(now?: number, toFake?: string[]): Clock; -export declare function install(context?: any, now?: number, toFake?: string[]): Clock; +/** + * Creates a clock and installs it globally. + * + * @param now Current time for the clock, as with lolex.createClock(). + * @param toFake Names of methods that should be faked. + * @type TClock Type of clock to create. + * @usage lolex.install(["setTimeout", "clearTimeout"]); + */ +export declare function install(now?: number | Date, toFake?: FakeMethod[]): TClock; + +/** + * Creates a clock and installs it onto the context object. + * + * @param context Context to install the clock onto. + * @param now Current time for the clock, as with lolex.createClock(). + * @param toFake Names of methods that should be faked. + * @type TClock Type of clock to create. + * @usage lolex.install(context, ["setTimeout", "clearTimeout"]); + */ +export declare function install(context?: any, now?: number | Date, toFake?: FakeMethod[]): TClock; diff --git a/lolex/lolex-tests.ts b/lolex/lolex-tests.ts index 00feecfdd6..876e4280c5 100644 --- a/lolex/lolex-tests.ts +++ b/lolex/lolex-tests.ts @@ -1,126 +1,84 @@ - import lolex = require("lolex"); -function a() { - var clock = lolex.createClock(); +let browserClock: lolex.BrowserClock = lolex.createClock() as lolex.BrowserClock; +let nodeClock: lolex.NodeClock = lolex.createClock() as lolex.NodeClock; - clock.setTimeout(function () { - console.log("The poblano is a mild chili pepper originating in the state of Puebla, Mexico."); - }, 15); +browserClock = lolex.createClock(); +nodeClock = lolex.createClock(); - // ... +lolex.createClock(7); +lolex.createClock(new Date()); +lolex.createClock(7, 9001); +lolex.createClock(new Date(), 9001); - clock.tick(15); -} +lolex.createClock(7); +lolex.createClock(new Date()); +lolex.createClock(7, 9001); +lolex.createClock(new Date(), 9001); -function b() { - var clock = lolex.install(window); +lolex.install(7); +lolex.install(new Date()); +lolex.install(7, ["setTimeout"]); +lolex.install(new Date(), ["setTimeout"]); - window.setTimeout(() => {}, 15); // Schedules with clock.setTimeout +lolex.install(7); +lolex.install(new Date()); +lolex.install(7, ["setTimeout"]); +lolex.install(new Date(), ["setTimeout"]); - clock.uninstall(); +lolex.install({}, 7); +lolex.install({}, new Date()); +lolex.install({}, 7, ["setTimeout"]); +lolex.install({}, new Date(), ["setTimeout"]); - // window.setTimeout is restored to the native implementation -} +lolex.install({}, 7); +lolex.install({}, new Date()); +lolex.install({}, 7, ["setTimeout"]); +lolex.install({}, new Date(), ["setTimeout"]); -function c() { - var clock = lolex.install(); +const browserNow: number = browserClock.now; +const browserDate: Date = new browserClock.Date(); - // Equivalent to - // var clock = lolex.install(typeof global !== "undefined" ? global : window); -} +const nodeNow: number = nodeClock.now; +const nodeDate: Date = new nodeClock.Date(); -var clock: lolex.Clock; +const browserTimeout: number = browserClock.setTimeout(() => {}, 7); +const browserInterval: number = browserClock.setInterval(() => {}, 7); +const browserImmediate: number = browserClock.setImmediate(() => {}); +const nodeTimeout: lolex.NodeTimer = nodeClock.setTimeout(() => {}, 7); +const nodeInterval: lolex.NodeTimer = nodeClock.setInterval(() => {}, 7); +const nodeImmediate: lolex.NodeTimer = nodeClock.setImmediate(() => {}); -/** - * var clock = lolex.createClock([now]) - */ +browserClock.clearTimeout(browserTimeout); +browserClock.clearInterval(browserInterval); +browserClock.clearImmediate(browserImmediate); -clock = lolex.createClock(); -clock = lolex.createClock(Date.now()); +nodeClock.clearTimeout(nodeTimeout); +nodeClock.clearInterval(nodeInterval); +nodeClock.clearImmediate(nodeImmediate); +browserClock.tick(7); +browserClock.tick("08"); -/** - * var clock = lolex.install([context[, now[, toFake]]]) - */ +nodeClock.tick(7); +nodeClock.tick("08"); -clock = lolex.install(); -clock = lolex.install(window); -clock = lolex.install(window, Date.now()); -clock = lolex.install(window, Date.now(), ['setTimeout', 'clearTimeout']); +browserClock.next(); +nodeClock.next(); +browserClock.runAll(); +nodeClock.runAll(); -/** - * var clock = lolex.install([now[, toFake]]) - */ +browserClock.runToLast(); +nodeClock.runToLast(); -clock = lolex.install(Date.now()); -clock = lolex.install(Date.now(), ['setTimeout', 'clearTimeout']); +browserClock.setSystemTime(); +browserClock.setSystemTime(7); +browserClock.setSystemTime(new Date()); -/** - * clock.now - */ -var n: number = clock.now; - - -var id: number; -/** - * var id = clock.setTimeout(callback, timeout) - */ - -id = clock.setTimeout(() => {}, 1000); - - -/** - * clock.clearTimeout(id) - */ - -clock.clearTimeout(id); - - -/** - * var id = clock.setInterval(callback, timeout) - */ - -id = clock.setInterval(() => {}, 1000); - - -/** - * clock.clearInterval(id) - */ - -clock.clearInterval(id); - - -/** - * var id = clock.setImmediate(callback) - */ - -id = clock.setImmediate(() => {}); - - -/** - * clock.clearImmediate(id) - */ - -clock.clearImmediate(id); - -/** - * clock.setSystemTime - */ -clock.setSystemTime(0); -clock.setSystemTime(new Date()); - -/** - * clock.tick(time) - */ - -clock.tick(1000); - - -/** - * clock.uninstall() - */ - -clock.uninstall(); +nodeClock.setSystemTime(); +nodeClock.setSystemTime(7); +nodeClock.setSystemTime(new Date()); +browserClock.uninstall(); +nodeClock.uninstall(); From da89aa8fe1779e552a6af16d103f396bb8b9f852 Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Sat, 14 Jan 2017 22:26:16 -0800 Subject: [PATCH 04/72] Bumped lolex version in index.d.ts --- lolex/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lolex/index.d.ts b/lolex/index.d.ts index 7a03b3fd2c..845a99afe6 100644 --- a/lolex/index.d.ts +++ b/lolex/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for lolex 1.5.1 +// Type definitions for lolex 1.5.2 // Project: https://github.com/sinonjs/lolex // Definitions by: Wim Looman , Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 19dea02c4cce0fe002374ffacea2ba54513039ab Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Sat, 14 Jan 2017 22:27:51 -0800 Subject: [PATCH 05/72] Fixed linting errors in index.d.ts --- lolex/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lolex/index.d.ts b/lolex/index.d.ts index 845a99afe6..de08060883 100644 --- a/lolex/index.d.ts +++ b/lolex/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for lolex 1.5.2 +// Type definitions for lolex 1.5 // Project: https://github.com/sinonjs/lolex // Definitions by: Wim Looman , Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ /** * Timer object used in node. */ -export type NodeTimer = { +export interface NodeTimer { /** * Stub method call. Does nothing. */ @@ -26,12 +26,12 @@ export type TimerId = number | NodeTimer; /** * Lolex clock for a browser environment. */ -type BrowserClock = IClock; +type BrowserClock = LolexClock; /** * Lolex clock for a Node environment. */ -type NodeClock = IClock & { +type NodeClock = LolexClock & { /** * Mimicks process.hrtime(). * @@ -39,7 +39,7 @@ type NodeClock = IClock & { * @returns High resolution real time as [seconds, nanoseconds]. */ hrtime(prevTime?: [number, number]): [number, number]; -} +}; /** * Clock object created by lolex. @@ -54,7 +54,7 @@ type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmedia /** * Controls the flow of time. */ -export interface IClock { +export interface LolexClock { /** * Current clock time. */ From e75f2831a3f347a88e604044fa21a5360940698e Mon Sep 17 00:00:00 2001 From: Benjamin Lim Date: Sun, 15 Jan 2017 23:22:20 +0800 Subject: [PATCH 06/72] feat: add performance options to webpack --- webpack/index.d.ts | 23 ++++++++++++++++++++++- webpack/webpack-tests.ts | 13 +++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/webpack/index.d.ts b/webpack/index.d.ts index c2a435da6e..820e76866b 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for webpack 2.2 // Project: https://github.com/webpack/webpack -// Definitions by: Qubo , Matt Lewis +// Definitions by: Qubo , Matt Lewis , Benjamin Lim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -66,6 +66,8 @@ declare namespace webpack { plugins?: Plugin[]; /** Stats options for logging */ stats?: compiler.StatsToStringOptions; + /** Performance options */ + performance?: PerformanceOptions; } interface Entry { @@ -845,6 +847,25 @@ declare namespace webpack { type CompilerCallback = (err: Error, stats: Stats) => void } + + interface PerformanceOptions { + /** + * Turns hints on/off. In addition, tells webpack to throw either an error or a warning when hints are found. This property is set to "warning" by default. + */ + hints?: boolean | 'error' | 'warning'; + /** + * An entrypoint represents all assets that would be utilized during initial load time for a specific entry. This option controls when webpack should emit performance hints based on the maximum entrypoint size. The default value is 250000 (bytes). + */ + maxEntryPointSize?: number; + /** + * An asset is any emitted file from webpack. This option controls when webpack emits a performance hint based on individual asset size. The default value is 250000 (bytes). + */ + maxAssetSize?: number; + /** + * This property allows webpack to control what files are used to calculate performance hints. + */ + assetFilter?: (assetFilename: string) => boolean; + } } declare var webpack: webpack.Webpack; diff --git a/webpack/webpack-tests.ts b/webpack/webpack-tests.ts index 8cdb92c94b..3900524ec5 100644 --- a/webpack/webpack-tests.ts +++ b/webpack/webpack-tests.ts @@ -490,3 +490,16 @@ configuration = { const resolve: webpack.Resolve = { cachePredicate: 'boo' // why does this test _not_ fail!? } + +const performance: webpack.PerformanceOptions = { + hints: 'error', + maxEntryPointSize: 400000, + maxAssetSize: 100000, + assetFilter: function(assetFilename) { + return assetFilename.endsWith('.js'); + }, +}; + +configuration = { + performance, +}; From 73e0c1cae3746f17aa2ddefcd5ebae34a923c1cf Mon Sep 17 00:00:00 2001 From: Benjamin Lim Date: Sun, 15 Jan 2017 23:23:05 +0800 Subject: [PATCH 07/72] style: fix lint errors --- webpack/index.d.ts | 67 +++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/webpack/index.d.ts b/webpack/index.d.ts index 820e76866b..577b96de2f 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -3,9 +3,6 @@ // Definitions by: Qubo , Matt Lewis , Benjamin Lim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - import * as UglifyJS from 'uglify-js'; import * as tapable from 'tapable'; @@ -278,14 +275,14 @@ declare namespace webpack { * * @deprecated Replaced by `mainFields` in webpack 2. */ - packageMains?: (string | string[])[]; + packageMains?: Array; /** * Check this field in the package.json for an object. Key-value-pairs are threaded as aliasing according to this spec * * @deprecated Replaced by `aliasFields` in webpack 2. */ - packageAlias?: (string | string[])[]; + packageAlias?: Array; /** * Enable aggressive but unsafe caching for the resolving of a part of your files. @@ -323,9 +320,7 @@ declare namespace webpack { [key: string]: boolean | string; } - interface ExternalsFunctionElement { - (context: any, request: any, callback: (error: any, result: any) => void): any; - } + type ExternalsFunctionElement = (context: any, request: any, callback: (error: any, result: any) => void) => any; interface WatchOptions { /** Delay the rebuilt after the first change. Value is a time in ms. */ @@ -469,7 +464,7 @@ declare namespace webpack { type Rule = LoaderRule | UseRule | RulesRule | OneOfRule; interface Plugin extends tapable.Plugin { - apply (thisArg: Webpack, ...args: any[]): void + apply(thisArg: Webpack, ...args: any[]): void; } interface Webpack { @@ -620,7 +615,7 @@ declare namespace webpack { } interface ContextReplacementPluginStatic { - new (resourceRegExp: any, newContentResource?: any, newContentRecursive?: any, newContentRegExp?: any): Plugin + new (resourceRegExp: any, newContentResource?: any, newContentRecursive?: any, newContentRegExp?: any): Plugin; } interface IgnorePluginStatic { @@ -666,31 +661,31 @@ declare namespace webpack { interface SourceMapDevToolPluginOptions { // output filename pattern (false/null to append) - filename?: string | false | null, + filename?: string | false | null; // source map comment pattern (false to not append) - append?: false | string, + append?: false | string; // template for the module filename inside the source map - moduleFilenameTemplate?: string, + moduleFilenameTemplate?: string; // fallback used when the moduleFilenameTemplate produces a collision - fallbackModuleFilenameTemplate?: string, + fallbackModuleFilenameTemplate?: string; // test/include/exclude files - test?: Condition | Condition[], - include?: Condition | Condition[], - exclude?: Condition | Condition[] + test?: Condition | Condition[]; + include?: Condition | Condition[]; + exclude?: Condition | Condition[]; // whether to include the footer comment with source information - noSources?: boolean, + noSources?: boolean; // the source map sourceRoot ("The URL root from which all sources are relative.") - sourceRoot?: string | null, + sourceRoot?: string | null; // whether to generate per-module source map - module?: boolean, + module?: boolean; // whether to include column information in the source map - columns?: boolean, + columns?: boolean; // whether to preserve line numbers between source and source map lineToLine?: boolean | { - test?: Condition | Condition[], - include?: Condition | Condition[], - exclude?: Condition | Condition[] - } + test?: Condition | Condition[]; + include?: Condition | Condition[]; + exclude?: Condition | Condition[]; + }; } interface EvalSourceMapDevToolPluginStatic { @@ -699,16 +694,16 @@ declare namespace webpack { } interface EvalSourceMapDevToolPluginOptions { - append?: false | string, - moduleFilenameTemplate?: string, - sourceRoot?: string, - module?: boolean, - columns?: boolean, + append?: false | string; + moduleFilenameTemplate?: string; + sourceRoot?: string; + module?: boolean; + columns?: boolean; lineToLine?: boolean | { - test?: Condition | Condition[], - include?: Condition | Condition[], - exclude?: Condition | Condition[] - } + test?: Condition | Condition[]; + include?: Condition | Condition[]; + exclude?: Condition | Condition[]; + }; } interface HotModuleReplacementPluginStatic { @@ -740,7 +735,7 @@ declare namespace webpack { new (): Plugin; } interface LimitChunkCountPluginStatic { - new (options: any): Plugin + new (options: any): Plugin; } interface MinChunkSizePluginStatic { new (options: any): Plugin; @@ -845,7 +840,7 @@ declare namespace webpack { colors?: boolean; } - type CompilerCallback = (err: Error, stats: Stats) => void + type CompilerCallback = (err: Error, stats: Stats) => void; } interface PerformanceOptions { From a1c40dc709822a73dd44b33dc3045fb459d337b9 Mon Sep 17 00:00:00 2001 From: Benjamin Lim Date: Sun, 15 Jan 2017 23:51:16 +0800 Subject: [PATCH 08/72] chore: disable tslint rules --- webpack/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webpack/index.d.ts b/webpack/index.d.ts index 577b96de2f..3ac0cc360f 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -363,6 +363,7 @@ declare namespace webpack { } type ConditionSpec = TestConditionSpec | OrConditionSpec | AndConditionSpec | NotConditionSpec; + // tslint:disable-next-line:no-empty-interface interface ConditionArray extends Array {} type Condition = string | RegExp | ((absPath: string) => boolean) | ConditionSpec | ConditionArray; @@ -623,6 +624,7 @@ declare namespace webpack { } interface PrefetchPluginStatic { + // tslint:disable-next-line:unified-signatures new (context: any, request: any): Plugin; new (request: any): Plugin; } From a597e01521c83998d3570a39fe8124494363ee67 Mon Sep 17 00:00:00 2001 From: Dan Marshall Date: Sun, 15 Jan 2017 12:07:43 -0800 Subject: [PATCH 09/72] update to maker.js 0.9.31 --- maker.js/index.d.ts | 204 ++++++++++++++++++++++++++++++++++--- maker.js/maker.js-tests.ts | 45 +++++++- 2 files changed, 236 insertions(+), 13 deletions(-) diff --git a/maker.js/index.d.ts b/maker.js/index.d.ts index 7cf55d0448..113b142cb8 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -17,6 +17,23 @@ * */ declare namespace MakerJs { + /** + * Version info + */ + var version: string; + /** + * Enumeration of environment types. + */ + var environmentTypes: { + BrowserUI: string; + NodeJs: string; + WebWorker: string; + Unknown: string; + }; + /** + * Current execution environment type, should be one of environmentTypes. + */ + var environment: string; /** * String-based enumeration of unit types: imperial, metric or otherwise. * A model may specify the unit system it is using, if any. When importing a model, it may have different units. @@ -543,6 +560,10 @@ declare namespace MakerJs { * The endpoints of the path, in absolute coords. */ endPoints: IPoint[]; + /** + * Length of the path. + */ + pathLength: number; } /** * A chain of paths which connect end to end. @@ -556,7 +577,17 @@ declare namespace MakerJs { * Flag if this chain forms a loop end to end. */ endless?: boolean; + /** + * Total length of all paths in the chain. + */ + pathLength: number; } + /** + * Test to see if an object implements the required properties of a chain. + * + * @param item The item to test. + */ + function isChain(item: any): boolean; /** * Callback to model.findChains() with resulting array of chains and unchained paths. */ @@ -839,7 +870,7 @@ declare namespace MakerJs.point { * @param rotationOrigin The center point of rotation. * @returns A new point. */ - function rotate(pointToRotate: IPoint, angleInDegrees: number, rotationOrigin: IPoint): IPoint; + function rotate(pointToRotate: IPoint, angleInDegrees: number, rotationOrigin?: IPoint): IPoint; /** * Scale a point's coordinates. * @@ -923,7 +954,7 @@ declare namespace MakerJs.path { * @param rotationOrigin The center point of rotation. * @returns The original path (for chaining). */ - function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin: IPoint): IPath; + function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin?: IPoint): IPath; /** * Scale a path. * @@ -950,6 +981,34 @@ declare namespace MakerJs.path { * @param useOriginB Optional flag to converge the origin point of lineB instead of the end point. */ function converge(lineA: IPathLine, lineB: IPathLine, useOriginA?: boolean, useOriginB?: boolean): IPoint; + /** + * Get points along a path. + * + * @param pathContext Path to get points from. + * @param numberOfPoints Number of points to divide the path. + * @returns Array of points which are on the path spread at a uniform interval. + */ + function toPoints(pathContext: IPath, numberOfPoints: number): IPoint[]; + /** + * Get key points (a minimal a number of points) along a path. + * + * @param pathContext Path to get points from. + * @param maxArcFacet Optional maximum length between points on an arc or circle. + * @returns Array of points which are on the path. + */ + function toKeyPoints(pathContext: IPath, maxArcFacet?: number): IPoint[]; + /** + * Center a path at [0, 0]. + * + * @param pathToCenter The path to center. + */ + function center(pathToCenter: IPath): IPath; + /** + * Move a path so its bounding box begins at [0, 0]. + * + * @param pathToZero The path to zero. + */ + function zero(pathToZero: IPath): IPath; } declare namespace MakerJs.path { /** @@ -1140,6 +1199,12 @@ declare namespace MakerJs.model { * @param origin Optional offset reference point. */ function originate(modelToOriginate: IModel, origin?: IPoint): IModel; + /** + * Center a model at [0, 0]. + * + * @param modelToCenter The model to center. + */ + function center(modelToCenter: IModel): IModel; /** * Create a clone of a model, mirrored on either or both x and y axes. * @@ -1181,7 +1246,7 @@ declare namespace MakerJs.model { * @param rotationOrigin The center point of rotation. * @returns The original model (for chaining). */ - function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin: IPoint): IModel; + function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin?: IPoint): IModel; /** * Scale a model. * @@ -1215,6 +1280,12 @@ declare namespace MakerJs.model { * @param modelCallbackAfterWalk Callback for each model after recursion. */ function walk(modelContext: IModel, options: IWalkOptions): void; + /** + * Move a model so its bounding box begins at [0, 0]. + * + * @param modelToZero The model to zero. + */ + function zero(modelToZero: IModel): IModel; } declare namespace MakerJs.model { /** @@ -1321,10 +1392,11 @@ declare namespace MakerJs.path { * * @param arc Arc to straighten. * @param bevel Optional flag to bevel the angle to prevent it from being too sharp. - * @param prefix Optional prefix to apply to path ids. + * @param prefix Optional string prefix to apply to path ids. + * @param close Optional flag to make a closed geometry by connecting the endpoints. * @returns Model of straight lines with same endpoints as the arc. */ - function straighten(arc: IPathArc, bevel?: boolean, prefix?: string): IModel; + function straighten(arc: IPathArc, bevel?: boolean, prefix?: string, close?: boolean): IModel; } declare namespace MakerJs.model { /** @@ -1423,7 +1495,7 @@ declare namespace MakerJs.measure { * @param arcA The arc to test. * @param arcB The arc to check for overlap. * @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps. - * @returns Boolean true if arc1 is overlapped with arcB. + * @returns Boolean true if arcA is overlapped with arcB. */ function isArcOverlapping(arcA: IPathArc, arcB: IPathArc, excludeTangents: boolean): boolean; /** @@ -1467,7 +1539,7 @@ declare namespace MakerJs.measure { * @param lineA The line to test. * @param lineB The line to check for overlap. * @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps. - * @returns Boolean true if line1 is overlapped with lineB. + * @returns Boolean true if lineA is overlapped with lineB. */ function isLineOverlapping(lineA: IPathLine, lineB: IPathLine, excludeTangents: boolean): boolean; /** @@ -1475,7 +1547,7 @@ declare namespace MakerJs.measure { * * @param measureA The measurement to test. * @param measureB The measurement to check for overlap. - * @returns Boolean true if measure1 is overlapped with measureB. + * @returns Boolean true if measureA is overlapped with measureB. */ function isMeasurementOverlapping(measureA: IMeasure, measureB: IMeasure): boolean; /** @@ -1665,10 +1737,22 @@ declare namespace MakerJs.path { * * @param pathA First path to fillet, which will be modified to fit the fillet. * @param pathB Second path to fillet, which will be modified to fit the fillet. + * @param filletRadius Radius of the fillet. + * @param options Optional IPointMatchOptions object to specify pointMatchingDistance. * @returns Arc path object of the new fillet. */ function fillet(pathA: IPath, pathB: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc; } +declare namespace MakerJs.chain { + /** + * Adds a fillet between each link in a chain. Each path will be cropped to fit a fillet, and all fillets will be returned as paths in a returned model object. + * + * @param chainToFillet The chain to add fillets to. + * @param filletRadius Radius of the fillet. + * @returns Model object containing paths which fillet the joints in the chain. + */ + function fillet(chainToFillet: IChain, filletRadius: number): IModel; +} declare namespace MakerJs.kit { /** * Helper function to use the JavaScript "apply" function in conjunction with the "new" keyword. @@ -1687,6 +1771,13 @@ declare namespace MakerJs.kit { function getParameterValues(ctor: IKit): any[]; } declare namespace MakerJs.model { + /** + * Find a single chain within a model, across all layers. Shorthand of findChains; useful when you know there is only one chain to find in your model. + * + * @param modelContext The model to search for a chain. + * @returns A chain object or null if chains were not found. + */ + function findSingleChain(modelContext: IModel): IChain; /** * Find paths that have common endpoints and form chains. * @@ -1695,6 +1786,25 @@ declare namespace MakerJs.model { */ function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; } +declare namespace MakerJs.chain { + /** + * Get points along a chain of paths. + * + * @param chainContext Chain of paths to get points from. + * @param distance Distance along the chain between points. + * @param maxPoints Maximum number of points to retrieve. + * @returns Array of points which are on the chain spread at a uniform interval. + */ + function toPoints(chainContext: IChain, distance: number, maxPoints?: number): IPoint[]; + /** + * Get key points (a minimal a number of points) along a chain of paths. + * + * @param chainContext Chain of paths to get points from. + * @param maxArcFacet The maximum length between points on an arc or circle. + * @returns Array of points which are on the chain. + */ + function toKeyPoints(chainContext: IChain, maxArcFacet?: number): IPoint[]; +} declare namespace MakerJs.model { /** * Find paths that have common endpoints and form loops. @@ -1836,14 +1946,29 @@ declare namespace MakerJs.exporter { } } declare namespace MakerJs.exporter { + /** + * Map of SVG Path Data by layer name. + */ + interface IPathDataByLayerMap { + [layer: string]: string; + } /** * Convert a chain to SVG path data. */ - function chainToSVGPathData(chain: IChain, offset: IPoint, scale: number): string; + function chainToSVGPathData(chain: IChain, offset: IPoint): string; /** * Convert a path to SVG path data. */ - function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint, scale: number): string; + function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint): string; + /** + * Convert a model to SVG path data. + * + * @param modelToExport Model to export. + * @param byLayers Boolean flag (default true) to return a map of path data by layer. + * @param origin Optional reference origin. + * @returns String of SVG path data (if byLayers is false) or an object map of path data by layer . + */ + function toSVGPathData(modelToExport: IModel, byLayers?: boolean, origin?: IPoint): IPathDataByLayerMap | string; function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string; function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string; function toSVG(pathToExport: IPath, options?: ISVGRenderOptions): string; @@ -1925,6 +2050,7 @@ declare namespace MakerJs.models { constructor(origin: IPoint, control1: IPoint, control2: IPoint, end: IPoint, accuracy?: number); static typeName: string; static getBezierSeeds(curve: BezierCurve, options?: IFindChainsOptions): IPathBezierSeed[]; + static computeLength(seed: IPathBezierSeed): number; static computePoint(seed: IPathBezierSeed, t: number): IPoint; } } @@ -2030,6 +2156,28 @@ declare namespace MakerJs.models { static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean): IPoint[]; } } +declare namespace MakerJs.models { + class Holes implements IModel { + paths: IPathMap; + /** + * Create an array of circles of the same radius from an array of center points. + * + * Example: + * ``` + * //Create some holes from an array of points + * var makerjs = require('makerjs'); + * var model = new makerjs.models.Holes(10, [[0, 0],[50, 0],[25, 40]]); + * var svg = makerjs.exporter.toSVG(model); + * document.write(svg); + * ``` + * + * @param holeRadius Hole radius. + * @param points Array of points for origin of each hole. + * @param ids Optional array of corresponding path ids for the holes. + */ + constructor(holeRadius: number, points: IPoint[], ids?: string[]); + } +} declare namespace MakerJs.models { class BoltCircle implements IModel { paths: IPathMap; @@ -2042,6 +2190,26 @@ declare namespace MakerJs.models { constructor(width: number, height: number, holeRadius: number); } } +declare namespace MakerJs.models { + class Dogbone implements IModel { + paths: IPathMap; + /** + * Create a dogbone from width, height, corner radius, style, and bottomless flag. + * + * Example: + * ``` + * var d = new makerjs.models.Dogbone(50, 100, 5); + * ``` + * + * @param width Width of the rectangle. + * @param height Height of the rectangle. + * @param radius Corner radius. + * @param style Optional corner style: 0 (default) for dogbone, 1 for vertical, -1 for horizontal. + * @param bottomless Optional flag to omit the bottom line and bottom corners (default false). + */ + constructor(width: number, height: number, radius: number, style?: number, bottomless?: boolean); + } +} declare namespace MakerJs.models { class Dome implements IModel { paths: IPathMap; @@ -2102,7 +2270,11 @@ declare namespace MakerJs.models { * * Example: * ``` - * var r = new makerjs.models.Rectangle(100, 50); + * //Create a rectangle from width and height + * var makerjs = require('makerjs'); + * var model = new makerjs.models.Rectangle(50, 100); + * var svg = makerjs.exporter.toSVG(model); + * document.write(svg); * ``` * * @param width Width of the rectangle. @@ -2114,8 +2286,12 @@ declare namespace MakerJs.models { * * Example: * ``` + * //Create a rectangle which will surround a model + * var makerjs = require('makerjs'); * var e = new makerjs.models.Ellipse(17, 10); // draw an ellipse so we have something to surround. * var r = new makerjs.models.Rectangle(e, 3); // draws a rectangle surrounding the ellipse by 3 units. + * var svg = makerjs.exporter.toSVG({ models: { e: e, r: r }}); + * document.write(svg); * ``` * * @param modelToSurround IModel object. @@ -2127,9 +2303,13 @@ declare namespace MakerJs.models { * * Example: * ``` + * //Create a rectangle from a measurement. + * var makerjs = require('makerjs'); * var e = new makerjs.models.Ellipse(17, 10); // draw an ellipse so we have something to measure. * var m = makerjs.measure.modelExtents(e); // measure the ellipse. * var r = new makerjs.models.Rectangle(m); // draws a rectangle surrounding the ellipse. + * var svg = makerjs.exporter.toSVG({ models: { e: e, r: r }}); + * document.write(svg); * ``` * * @param measurement IMeasure object. See http://microsoft.github.io/maker.js/docs/api/modules/makerjs.measure.html#pathextents and http://microsoft.github.io/maker.js/docs/api/modules/makerjs.measure.html#modelextents to get measurements of paths and models. @@ -2173,6 +2353,6 @@ declare namespace MakerJs.models { declare namespace MakerJs.models { class Text implements IModel { models: IModelMap; - constructor(font: opentype.Font, text: string, fontSize: number, combine?: boolean); + constructor(font: opentype.Font, text: string, fontSize: number, combine?: boolean, centerCharacterOrigin?: boolean, bezierAccuracy?: number); } } diff --git a/maker.js/maker.js-tests.ts b/maker.js/maker.js-tests.ts index cc7cc0804d..4c7dbc25f0 100644 --- a/maker.js/maker.js-tests.ts +++ b/maker.js/maker.js-tests.ts @@ -9,11 +9,36 @@ function test() { var paths = testPaths(); var models = testModels(); var model: MakerJs.IModel = models[0]; + var seed: MakerJs.IPathBezierSeed = { type: makerjs.pathType.BezierSeed, origin: [0,0], end: [1,1], controls: []}; + var chain: MakerJs.IChain = { + endless: false, + links: [ + { + endPoints: [], + reversed: false, + pathLength: 0, + walkedPath: { + layer: '', + modelContext: model, + offset: p1, + pathContext: paths.line, + pathId: 'x', + route: [], + routeKey: '' + } + } + ], + pathLength: 0 + }; function testRoot() { + makerjs.version; + makerjs.environment; + makerjs.environmentTypes.BrowserUI; makerjs.cloneObject({}); makerjs.createRouteKey([]); makerjs.extendObject({abc:123}, {xyz:789}); + makerjs.isChain({}); makerjs.isFunction(function(){}); makerjs.isNumber(0); makerjs.isObject({}); @@ -62,6 +87,7 @@ function test() { useSvgPathOnly: false, viewBox: false }); + makerjs.exporter.toSVGPathData(model); makerjs.exporter.tryGetModelUnits(model); } @@ -88,7 +114,7 @@ function test() { makerjs.measure.isBetween(7, 8, 9, false); makerjs.measure.isBetweenArcAngles(7, paths.arc, false); makerjs.measure.isBetweenPoints([1,1], paths.line, true); - makerjs.measure.isBezierSeedLinear({type: '', origin:[], end:[], controls:[]}); + makerjs.measure.isBezierSeedLinear(seed); makerjs.measure.isLineOverlapping(paths.line, paths.line, false); makerjs.measure.isMeasurementOverlapping(mm, mp); var mm = makerjs.measure.modelExtents(model); @@ -105,6 +131,7 @@ function test() { function testModel(){ makerjs.model.breakPathsAtIntersections(model, { paths:{ } }); + makerjs.model.center(model); var opts: MakerJs.ICombineOptions = { trimDeadEnds: true, pointMatchingDistance: 2 }; makerjs.model.combine(model, model, true, false, true, false, opts); makerjs.model.combineIntersection(model, model); @@ -116,6 +143,7 @@ function test() { makerjs.model.expandPaths(model, 7); makerjs.model.findChains(model, function (chains: MakerJs.IChain[], loose: MakerJs.IWalkPath[], layer: string) {}) makerjs.model.findLoops(model); + makerjs.model.findSingleChain(model); makerjs.model.getSimilarModelId(model, 'foo'); makerjs.model.getSimilarPathId(model, 'foo'); makerjs.model.isPathInsideModel(paths.line, model); @@ -131,18 +159,24 @@ function test() { makerjs.model.simplify(model); makerjs.model.walk(model, {}); makerjs.model.walkPaths(model, (modelContext: MakerJs.IModel, pathId: string, pathContext: MakerJs.IPath) => {}); + makerjs.model.zero(model); model.exporterOptions = { foo: 'bar' }; } function testModels(): MakerJs.IModel[] { + makerjs.models.BezierCurve.computeLength(seed); + makerjs.models.BezierCurve.computePoint(seed, 0); + makerjs.models.BezierCurve.getBezierSeeds(new makerjs.models.BezierCurve([])); return [ new makerjs.models.BezierCurve([]), new makerjs.models.BoltCircle(7, 7, 7, 7), new makerjs.models.BoltRectangle(2, 2, 2), new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]), + new makerjs.models.Dogbone(1,1,1), new makerjs.models.Dome(5, 7), new makerjs.models.Ellipse(2,2), new makerjs.models.EllipticArc(2,2,3,4), + new makerjs.models.Holes(1,[]), new makerjs.models.Oval(7, 7), new makerjs.models.OvalArc(6, 4, 2, 12, true), new makerjs.models.Polygon(7, 5), @@ -159,6 +193,7 @@ function test() { function testPath() { makerjs.path.breakAtPoint(paths.arc, [0,0]).type; + makerjs.path.center(paths.line); makerjs.path.clone(paths.line); makerjs.path.converge(paths.line, paths.line); makerjs.path.distort(paths.arc, 5, 6); @@ -173,6 +208,8 @@ function test() { makerjs.path.rotate(paths.line, 5, [0,0]); makerjs.path.scale(paths.arc, 8); makerjs.path.straighten(paths.arc); + makerjs.path.toKeyPoints(paths.arc, 1); + makerjs.path.toPoints(paths.circle, 1); } function testPaths() { @@ -217,6 +254,12 @@ function test() { makerjs.point.zero(); } + function testChain() { + makerjs.chain.fillet(chain, 1); + makerjs.chain.toKeyPoints(chain); + makerjs.chain.toPoints(chain, 1); + } + function testSolvers() { makerjs.solvers.solveTriangleASA(4, 4, 4); makerjs.solvers.solveTriangleSSS(9, 9, 9); From 61ed8636d59627ffb81a96999b8273c9146108da Mon Sep 17 00:00:00 2001 From: Dan Marshall Date: Sun, 15 Jan 2017 12:34:09 -0800 Subject: [PATCH 10/72] added version number to header --- maker.js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maker.js/index.d.ts b/maker.js/index.d.ts index 113b142cb8..ad06d7eb91 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Maker.js +// Type definitions for Maker.js 0.9.31 // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 435590b7d2e0d87e759876ba01ab719a12c5945a Mon Sep 17 00:00:00 2001 From: "J.David" Date: Tue, 17 Jan 2017 13:25:05 +0100 Subject: [PATCH 11/72] [bson] remove old pure/native layout --- bson/bson-tests.ts | 9 +-- bson/index.d.ts | 162 +++++++++++++++++++++------------------------ 2 files changed, 79 insertions(+), 92 deletions(-) diff --git a/bson/bson-tests.ts b/bson/bson-tests.ts index e1e1c5d323..d18332fe9f 100644 --- a/bson/bson-tests.ts +++ b/bson/bson-tests.ts @@ -1,7 +1,7 @@ import * as bson from 'bson'; -let BSON = new bson.BSONPure.BSON(); -let Long = bson.BSONPure.Long; +let BSON = new bson.BSON(); +let Long = bson.Long; let doc = {long: Long.fromNumber(100)} @@ -13,9 +13,6 @@ console.log("data:", data); let doc_2 = BSON.deserialize(data); console.log("doc_2:", doc_2); - -BSON = new bson.BSONNative.BSON(); +BSON = new bson.BSON(); data = BSON.serialize(doc); doc_2 = BSON.deserialize(data); - - diff --git a/bson/index.d.ts b/bson/index.d.ts index 5c62f61433..c497297f20 100644 --- a/bson/index.d.ts +++ b/bson/index.d.ts @@ -5,92 +5,82 @@ /// -declare namespace bson { - - export namespace BSONPure { - export interface DeserializeOptions { - /** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */ - evalFunctions?: boolean; - /** {Boolean, default:false}, cache evaluated functions for reuse. */ - cacheFunctions?: boolean; - /** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */ - cacheFunctionsCrc32?: boolean; - /** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */ - promoteBuffers?: boolean; - } - export class BSON { - /** - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore). - * @param {Boolean} serializeFunctions serialize the javascript functions (default:false) - * @return {Buffer} returns a TypedArray or Array depending on what your browser supports - */ - serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer; - deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any; - } - - export class Binary { - static SUBTYPE_DEFAULT: number; - static SUBTYPE_FUNCTION: number; - static SUBTYPE_BYTE_ARRAY: number; - static SUBTYPE_UUID_OLD: number; - static SUBTYPE_UUID: number; - static SUBTYPE_MD5: number; - static SUBTYPE_USER_DEFINED: number; - - constructor(buffer: Buffer, subType?: number); - } - export class Code { - constructor(code: string | Function, scope?: any); - } - export class DBRef { - constructor(namespace: string, oid: ObjectID, db?: string); - } - export class Double { - constructor (value: number); - } - export class Long { - static fromInt(i: number): Long; - static fromNumber(n: number): Long; - static fromBits(lowBits: number, highBits: number): Long; - static fromString(s: string, opt_radix?: number): Long; - - constructor(low: number, high: number); - } - export class MaxKey { - constructor(); - } - export class MinKey { - constructor(); - } - export class ObjectId { - static createPk(): ObjectId; - static createFromTime(time: number): ObjectId; - static createFromHexString(hexString: string): ObjectId; - static isValid(id: number | string | ObjectId): boolean; - - constructor(id?: number | string | ObjectId); - } - export type ObjectID = ObjectId; - export class BSONRegExp { - constructor(pattern: string, options: string); - } - export class Symbol { - constructor(value: string); - } - export class Timestamp { - static fromInt(i: number): Timestamp; - static fromNumber(n: number): Timestamp; - static fromBits(lowBits: number, highBits: number): Timestamp; - static fromString(s: string, opt_radix?: number): Timestamp; - - constructor(low: number, high: number); - } - } - export let BSONNative: typeof BSONPure; - +export interface DeserializeOptions { + /** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** {Boolean, default:false}, cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */ + cacheFunctionsCrc32?: boolean; + /** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */ + promoteBuffers?: boolean; +} +export class BSON { + /** + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore). + * @param {Boolean} serializeFunctions serialize the javascript functions (default:false) + * @return {Buffer} returns a TypedArray or Array depending on what your browser supports + */ + serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer; + deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any; } -export = bson; +export class Binary { + static SUBTYPE_DEFAULT: number; + static SUBTYPE_FUNCTION: number; + static SUBTYPE_BYTE_ARRAY: number; + static SUBTYPE_UUID_OLD: number; + static SUBTYPE_UUID: number; + static SUBTYPE_MD5: number; + static SUBTYPE_USER_DEFINED: number; + constructor(buffer: Buffer, subType?: number); +} +export class Code { + constructor(code: string | Function, scope?: any); +} +export class DBRef { + constructor(namespace: string, oid: ObjectID, db?: string); +} +export class Double { + constructor (value: number); +} +export class Long { + static fromInt(i: number): Long; + static fromNumber(n: number): Long; + static fromBits(lowBits: number, highBits: number): Long; + static fromString(s: string, opt_radix?: number): Long; + + constructor(low: number, high: number); +} +export class MaxKey { + constructor(); +} +export class MinKey { + constructor(); +} +export class ObjectId { + static createPk(): ObjectId; + static createFromTime(time: number): ObjectId; + static createFromHexString(hexString: string): ObjectId; + static isValid(id: number | string | ObjectId): boolean; + + constructor(id?: number | string | ObjectId); +} +export type ObjectID = ObjectId; +export class BSONRegExp { + constructor(pattern: string, options: string); +} +export class Symbol { + constructor(value: string); +} +export class Timestamp { + static fromInt(i: number): Timestamp; + static fromNumber(n: number): Timestamp; + static fromBits(lowBits: number, highBits: number): Timestamp; + static fromString(s: string, opt_radix?: number): Timestamp; + + constructor(low: number, high: number); +} From 7ec5b64a26d6b55e7f9511ae9fc5e9029535b468 Mon Sep 17 00:00:00 2001 From: "J.David" Date: Tue, 17 Jan 2017 13:53:25 +0100 Subject: [PATCH 12/72] Increase the version number in the header to 1.0 --- bson/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bson/index.d.ts b/bson/index.d.ts index c497297f20..517ed8ede9 100644 --- a/bson/index.d.ts +++ b/bson/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bson 0.4 +// Type definitions for bson 1.0 // Project: https://github.com/mongodb/js-bson // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From bfcd32a2bcdec6d78bbdebe72e8316d8a0c4a052 Mon Sep 17 00:00:00 2001 From: kevinmerckx Date: Tue, 17 Jan 2017 15:26:12 +0100 Subject: [PATCH 13/72] Update ITemplateLinkingFunction signature according to ng1.6 (#14041) * update $compile specs to latest angular 1 * fix(angular): ITemplateLinking function signature according to ng1.6 * revert(angularjs): revert added file angular.d.ts * angular: in ITemplateLinkingFunction replace any by IController --- angular/index.d.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/angular/index.d.ts b/angular/index.d.ts index bae6351cfb..f3f9fc87a6 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -1280,7 +1280,15 @@ declare namespace angular { // This corresponds to the "publicLinkFn" returned by $compile. interface ITemplateLinkingFunction { - (scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery; + (scope: IScope, cloneAttachFn?: ICloneAttachFunction, options?: ITemplateLinkingFunctionOptions): JQuery; + } + + interface ITemplateLinkingFunctionOptions { + parentBoundTranscludeFn?: ITranscludeFunction, + transcludeControllers?: { + [controller: string]: { instance: IController } + }, + futureParentElement?: JQuery } /** From 60e56c268fa43cee750cd410275f6d32dd4cf478 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 17 Jan 2017 08:06:10 -0800 Subject: [PATCH 14/72] react-router: Lint (#14063) --- react-router/index.d.ts | 6 ++--- react-router/lib/Route.d.ts | 4 ++-- react-router/lib/RouteContext.d.ts | 2 +- react-router/lib/Router.d.ts | 32 +++++++++++++------------- react-router/lib/routerHistory.d.ts | 10 ++++---- react-router/lib/useRouterHistory.d.ts | 6 +---- react-router/lib/withRouter.d.ts | 2 +- react-router/tslint.json | 7 ++++++ 8 files changed, 36 insertions(+), 33 deletions(-) create mode 100644 react-router/tslint.json diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 59f33e1960..80b1b97154 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-router v2.0.0 +// Type definitions for react-router 2.0 // Project: https://github.com/rackt/react-router // Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,9 +9,9 @@ export as namespace ReactRouter; import * as React from 'react'; -export const routerShape: React.Requireable +export const routerShape: React.Requireable; -export const locationShape: React.Requireable +export const locationShape: React.Requireable; import Router from "./lib/Router"; import Link from "./lib/Link"; diff --git a/react-router/lib/Route.d.ts b/react-router/lib/Route.d.ts index 2f5425b55a..cf1e6a7fc4 100644 --- a/react-router/lib/Route.d.ts +++ b/react-router/lib/Route.d.ts @@ -12,8 +12,8 @@ declare namespace self { path?: Router.RoutePattern; component?: Router.RouteComponent; components?: Router.RouteComponents; - getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void - getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void + getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void; onEnter?: Router.EnterHook; onLeave?: Router.LeaveHook; onChange?: Router.ChangeHook; diff --git a/react-router/lib/RouteContext.d.ts b/react-router/lib/RouteContext.d.ts index c35ab92a80..19225af17e 100644 --- a/react-router/lib/RouteContext.d.ts +++ b/react-router/lib/RouteContext.d.ts @@ -1,5 +1,5 @@ import * as React from 'react'; -declare const RouteContext: React.Mixin +declare const RouteContext: React.Mixin; export default RouteContext; diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index a9c5417f47..a7dff58369 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -16,7 +16,7 @@ export default Router; declare namespace Router { type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; type RoutePattern = string; - type RouteComponents = { [key: string]: RouteComponent }; + interface RouteComponents { [key: string]: RouteComponent; } type ParseQueryString = (queryString: QueryString) => Query; type StringifyQuery = (queryObject: Query) => QueryString; @@ -29,15 +29,15 @@ declare namespace Router { type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; type RouteHook = (nextLocation?: Location) => any; - type Params = { [param: string]: string }; + interface Params { [param: string]: string; } type RouterListener = (error: Error, nextState: RouterState) => void; - type LocationDescriptor = { - pathname?: Pathname - query?: Query - hash?: Href - state?: HLocationState + interface LocationDescriptor { + pathname?: Pathname; + query?: Query; + hash?: Href; + state?: HLocationState; } interface RedirectFunction { @@ -103,14 +103,14 @@ declare namespace Router { // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md interface InjectedRouter { - push: (pathOrLoc: Path | LocationDescriptor) => void - replace: (pathOrLoc: Path | LocationDescriptor) => void - go: (n: number) => void - goBack: () => void - goForward: () => void - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void - createPath(path: History.Path, query?: History.Query): History.Path - createHref(path: History.Path, query?: History.Query): History.Href - isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean + push: (pathOrLoc: Path | LocationDescriptor) => void; + replace: (pathOrLoc: Path | LocationDescriptor) => void; + go: (n: number) => void; + goBack: () => void; + goForward: () => void; + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void; + createPath(path: History.Path, query?: History.Query): History.Path; + createHref(path: History.Path, query?: History.Query): History.Href; + isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean; } } diff --git a/react-router/lib/routerHistory.d.ts b/react-router/lib/routerHistory.d.ts index 660af424b4..93558ff11f 100644 --- a/react-router/lib/routerHistory.d.ts +++ b/react-router/lib/routerHistory.d.ts @@ -4,11 +4,11 @@ import * as H from 'history'; export default History; export interface HistoryRoutes { - listen(listener: Router.RouterListener): Function - listenBeforeLeavingRoute(route: Router.PlainRoute, hook: Router.RouteHook): void - match(location: H.Location, callback: (error: any, nextState: Router.RouterState, nextLocation: H.Location) => void): void - isActive(pathname: H.Pathname, query?: H.Query, indexOnly?: boolean): boolean - setRouteLeaveHook(route: Router.PlainRoute, callback: Router.RouteHook): void + listen(listener: Router.RouterListener): Function; + listenBeforeLeavingRoute(route: Router.PlainRoute, hook: Router.RouteHook): void; + match(location: H.Location, callback: (error: any, nextState: Router.RouterState, nextLocation: H.Location) => void): void; + isActive(pathname: H.Pathname, query?: H.Query, indexOnly?: boolean): boolean; + setRouteLeaveHook(route: Router.PlainRoute, callback: Router.RouteHook): void; } export interface HistoryBase extends H.History { diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index d3e043b609..160375d2f0 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,7 +1,3 @@ import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; -interface CreateRouterHistory { - (options?: HistoryOptions): History & HistoryQueries; -} - -export default function useRouterHistory(createHistory: CreateHistory): CreateRouterHistory; +export default function useRouterHistory(createHistory: CreateHistory): (options?: HistoryOptions) => History & HistoryQueries; diff --git a/react-router/lib/withRouter.d.ts b/react-router/lib/withRouter.d.ts index f698d94fd0..71330bbb21 100644 --- a/react-router/lib/withRouter.d.ts +++ b/react-router/lib/withRouter.d.ts @@ -1,4 +1,4 @@ import * as React from 'react'; -declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C +declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C; export default withRouter; diff --git a/react-router/tslint.json b/react-router/tslint.json new file mode 100644 index 0000000000..e050abdce9 --- /dev/null +++ b/react-router/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "no-empty-interface": false + } +} \ No newline at end of file From cd116a2d2987acf2f8c5c7f0156a2f8f7ef8f7e7 Mon Sep 17 00:00:00 2001 From: Daniel Perez Alvarez Date: Tue, 17 Jan 2017 21:08:15 +0100 Subject: [PATCH 15/72] Add types for ip-regex 2.0.0 (#14069) --- ip-regex/index.d.ts | 12 ++++++++++++ ip-regex/ip-regex-tests.ts | 7 +++++++ ip-regex/tsconfig.json | 20 ++++++++++++++++++++ ip-regex/tslint.json | 1 + 4 files changed, 40 insertions(+) create mode 100644 ip-regex/index.d.ts create mode 100644 ip-regex/ip-regex-tests.ts create mode 100644 ip-regex/tsconfig.json create mode 100644 ip-regex/tslint.json diff --git a/ip-regex/index.d.ts b/ip-regex/index.d.ts new file mode 100644 index 0000000000..c26cbaab3b --- /dev/null +++ b/ip-regex/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for ip-regex 2.0 +// Project: https://github.com/sindresorhus/ip-regex +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Regular expression for matching IP addresses (IPv4 & IPv6). */ +declare function ipRegex(options?: { + /** Only match an exact string. Useful with RegExp#test to check if a string is an IP address. */ + exact?: boolean; +}): RegExp; + +export = ipRegex; diff --git a/ip-regex/ip-regex-tests.ts b/ip-regex/ip-regex-tests.ts new file mode 100644 index 0000000000..dcaa72c72d --- /dev/null +++ b/ip-regex/ip-regex-tests.ts @@ -0,0 +1,7 @@ +import ipRegex = require('ip-regex'); + +ipRegex().test('unicorn 192.168.0.1'); + +ipRegex({exact: true}).test('unicorn 192.168.0.1'); + +'unicorn 192.168.0.1 cake 1:2:3:4:5:6:7:8 rainbow'.match(ipRegex()); diff --git a/ip-regex/tsconfig.json b/ip-regex/tsconfig.json new file mode 100644 index 0000000000..5cb66f8d50 --- /dev/null +++ b/ip-regex/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ip-regex-tests.ts" + ] +} diff --git a/ip-regex/tslint.json b/ip-regex/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/ip-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From c4e848741d8a20cf0cc91635c958d94ddef2a8a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20Par=C3=A9?= Date: Tue, 17 Jan 2017 15:09:25 -0500 Subject: [PATCH 16/72] React input mask (#14068) * add react mask input * tsx do not work * regenerate with command line * tsx in tsconfig * maskChar accept null * lint --- react-input-mask/index.d.ts | 42 +++++++++++++++++++++ react-input-mask/react-input-mask-tests.tsx | 10 +++++ react-input-mask/tsconfig.json | 21 +++++++++++ react-input-mask/tslint.json | 1 + 4 files changed, 74 insertions(+) create mode 100644 react-input-mask/index.d.ts create mode 100644 react-input-mask/react-input-mask-tests.tsx create mode 100644 react-input-mask/tsconfig.json create mode 100644 react-input-mask/tslint.json diff --git a/react-input-mask/index.d.ts b/react-input-mask/index.d.ts new file mode 100644 index 0000000000..3764b61122 --- /dev/null +++ b/react-input-mask/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for react-input-mask 0.7 +// Project: https://github.com/sanniassin/react-input-mask +// Definitions by: Alexandre Paré +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from "react"; + +declare namespace reactInputMask { + export interface ReactInputMaskProps extends React.HTMLAttributes { + /** + * Mask string. Format characters are: + * * `9`: `0-9` + * * `a`: `A-Z, a-z` + * * `\*`: `A-Z, a-z, 0-9` + * + * Any character can be escaped with backslash, which usually will appear as double backslash in JS strings. For example, German phone mask with unremoveable prefix +49 will look like `mask="+4\\9 99 999 99"` or `mask={"+4\\\\9 99 999 99"}` + */ + mask: string; + /** + * Character to cover unfilled editable parts of mask. Default character is "_". If set to null, unfilled parts will be empty, like in ordinary input. + */ + maskChar?: string | null; + /** + * Defines format characters with characters as keys and corresponding RegExp string as values. Default ones: + * ``` + * { + * "9": "[0-9]", + * "a": "[A-Za-z]", + * "*": "[A-Za-z0-9]" + * }``` + */ + formatChars?: { [key: string]: string }; + /** + * Show mask even in empty input without focus. + */ + alwaysShowMask?: boolean; + } + export class ReactInputMask extends React.Component { + } +} +declare var ReactInputMask: typeof reactInputMask.ReactInputMask; +export = ReactInputMask; diff --git a/react-input-mask/react-input-mask-tests.tsx b/react-input-mask/react-input-mask-tests.tsx new file mode 100644 index 0000000000..955a6ce4b8 --- /dev/null +++ b/react-input-mask/react-input-mask-tests.tsx @@ -0,0 +1,10 @@ +import * as ReactInputMask from 'react-input-mask'; +import * as React from 'react'; + +
+ + + + + +
\ No newline at end of file diff --git a/react-input-mask/tsconfig.json b/react-input-mask/tsconfig.json new file mode 100644 index 0000000000..43fd3a083d --- /dev/null +++ b/react-input-mask/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-input-mask-tests.tsx" + ] +} diff --git a/react-input-mask/tslint.json b/react-input-mask/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-input-mask/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From bc12eadd2debe72f0c111126b293d66824edaf9d Mon Sep 17 00:00:00 2001 From: Daniel Perez Alvarez Date: Tue, 17 Jan 2017 21:10:39 +0100 Subject: [PATCH 17/72] Add types for url-regex 4.0.0 (#14067) --- url-regex/index.d.ts | 12 ++++++++++++ url-regex/tsconfig.json | 20 ++++++++++++++++++++ url-regex/tslint.json | 1 + url-regex/url-regex-tests.ts | 11 +++++++++++ 4 files changed, 44 insertions(+) create mode 100644 url-regex/index.d.ts create mode 100644 url-regex/tsconfig.json create mode 100644 url-regex/tslint.json create mode 100644 url-regex/url-regex-tests.ts diff --git a/url-regex/index.d.ts b/url-regex/index.d.ts new file mode 100644 index 0000000000..ed51c6e34d --- /dev/null +++ b/url-regex/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for url-regex 4.0 +// Project: https://github.com/kevva/url-regex +// Definitions by: Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Regular expression for matching URLs. */ +declare function urlRegex(options?: { + /** Only match an exact string. Useful with RegExp#test to check if a string is a URL. */ + exact?: boolean; +}): RegExp; + +export = urlRegex; diff --git a/url-regex/tsconfig.json b/url-regex/tsconfig.json new file mode 100644 index 0000000000..944db02afc --- /dev/null +++ b/url-regex/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "url-regex-tests.ts" + ] +} diff --git a/url-regex/tslint.json b/url-regex/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/url-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/url-regex/url-regex-tests.ts b/url-regex/url-regex-tests.ts new file mode 100644 index 0000000000..e7063604b6 --- /dev/null +++ b/url-regex/url-regex-tests.ts @@ -0,0 +1,11 @@ +import urlRegex = require('url-regex'); + +urlRegex().test('http://github.com foo bar'); + +urlRegex().test('www.github.com foo bar'); + +urlRegex({exact: true}).test('http://github.com foo bar'); + +urlRegex({exact: true}).test('http://github.com'); + +'foo http://github.com bar //google.com'.match(urlRegex()); From fbe3c79b6f39dfe2250cc4843d71930b7dae9cd9 Mon Sep 17 00:00:00 2001 From: Matthias Baumann Date: Tue, 17 Jan 2017 22:01:50 +0100 Subject: [PATCH 18/72] Update index.d.ts (#14060) Order of overloads matters - otherwise correct overload is not selected. --- deep-diff/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deep-diff/index.d.ts b/deep-diff/index.d.ts index a0becbf970..f07fc39ef6 100644 --- a/deep-diff/index.d.ts +++ b/deep-diff/index.d.ts @@ -22,9 +22,9 @@ declare namespace deepDiff { (path: string[], key: string): boolean; } - interface IDeepDiff { - diff(): IDiff; + interface IDeepDiff { diff(lhs: Object, rhs: Object, prefilter?: IPrefilter, acc?: IAccumulator): IDiff[]; + diff(): IDiff; observableDiff(lhs: Object, rhs: Object, changes: Function, prefilter?: IPrefilter, path?: string[], key?: string, stack?: Object[]): void; applyDiff(target: Object, source: Object, filter: Function): void; applyChange(target: Object, source: Object, change: IDiff): void; From 5a46416cea28c136aafb850d130ac604881a1260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=81aziuk?= Date: Tue, 17 Jan 2017 22:03:58 +0100 Subject: [PATCH 19/72] [simple-peer] new definition, version 6.1 (#14058) * simple-peer * formatting * contributors --- simple-peer/index.d.ts | 63 ++++++++++++++++++++++++++++++++ simple-peer/simple-peer-tests.ts | 7 ++++ simple-peer/tsconfig.json | 20 ++++++++++ simple-peer/tslint.json | 3 ++ 4 files changed, 93 insertions(+) create mode 100644 simple-peer/index.d.ts create mode 100644 simple-peer/simple-peer-tests.ts create mode 100644 simple-peer/tsconfig.json create mode 100644 simple-peer/tslint.json diff --git a/simple-peer/index.d.ts b/simple-peer/index.d.ts new file mode 100644 index 0000000000..86c7f08bfb --- /dev/null +++ b/simple-peer/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for simple-peer 6.1 +// Project: https://github.com/feross/simple-peer +// Definitions by: Tomasz Łaziuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as stream from 'stream'; + +declare const SimplePeer: SimplePeer.SimplePeer; + +declare namespace SimplePeer { + export interface Options { + initiator?: boolean; // set to true if this is the initiating peer + channelConfig?: {}; // custom webrtc data channel configuration (used by createDataChannel) + channelName?: string; // custom webrtc data channel name + config?: {}; // custom webrtc configuration (used by RTCPeerConnection constructor) + constraints?: {}; // custom webrtc video/voice constraints (used by RTCPeerConnection constructor) + offerConstraints?: {}; // custom offer constraints (used by createOffer method) + answerConstraints?: {}; // custom answer constraints (used by createAnswer method) + reconnectTimer?: boolean | number; // wait __ milliseconds after ICE 'disconnect' for reconnect attempt before emitting 'close' + sdpTransform?: (sdp: T) => T; // function to transform the generated SDP signaling data (for advanced users) + stream?: boolean; // if video/voice is desired, pass stream returned from getUserMedia + trickle?: boolean; // set to false to disable trickle ICE and get a single 'signal' event (slower) + wrtc?: {}; // RTCPeerConnection/RTCSessionDescription/RTCIceCandidate + } + + // https://github.com/feross/simple-peer/tree/v6.1.5#peer--new-simplepeeropts + export interface SimplePeer { + new (opts?: Options): Instance; + (opts?: Options): Instance; + + // https://github.com/feross/simple-peer/tree/v6.1.5#peerwebrtc_support + readonly WEBRTC_SUPPORT: boolean; + } + + export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; + + export type SimplePeerData = string | Buffer | TypedArray | ArrayBuffer | Blob; + + export interface SignalData { + sdp?: any; + candidate?: any; + } + + export interface Instance extends stream.Duplex { + + // https://github.com/feross/simple-peer/tree/v6.1.5#peersignaldata + signal(data: string | SignalData): void; + + // https://github.com/feross/simple-peer/tree/v6.1.5#peersenddata + send(data: SimplePeerData): void; + + // https://github.com/feross/simple-peer/tree/v6.1.5#peersenddata + destroy(onclose?: () => void): void; + + // methods which are not documented + readonly bufferSize: number; + address(): { port: string, family: string, address: string, }; + } +} + +export = SimplePeer; diff --git a/simple-peer/simple-peer-tests.ts b/simple-peer/simple-peer-tests.ts new file mode 100644 index 0000000000..97fa2e9e8e --- /dev/null +++ b/simple-peer/simple-peer-tests.ts @@ -0,0 +1,7 @@ +import * as SimplePeer from 'simple-peer'; + +const peer = new SimplePeer(); +peer.write(new Buffer('hey')); +peer.on('data', (chunk) => { + console.log(`got a chunk: ${chunk}`); +}); diff --git a/simple-peer/tsconfig.json b/simple-peer/tsconfig.json new file mode 100644 index 0000000000..1f68ffcf97 --- /dev/null +++ b/simple-peer/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simple-peer-tests.ts" + ] +} diff --git a/simple-peer/tslint.json b/simple-peer/tslint.json new file mode 100644 index 0000000000..ec365f164b --- /dev/null +++ b/simple-peer/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} From eccba27fb50f144d16707d21bf73625bed1be9a5 Mon Sep 17 00:00:00 2001 From: Chris Barker Date: Tue, 17 Jan 2017 21:07:16 +0000 Subject: [PATCH 20/72] Initial commit of typings for OpenFin API (#14054) * Initial commit of typings for OpenFin API * Minor revisions based on extended testing --- openfin/index.d.ts | 1493 ++++++++++++++++++++++++++++++++++++++ openfin/openfin-tests.ts | 718 ++++++++++++++++++ openfin/tsconfig.json | 20 + openfin/tslint.json | 1 + 4 files changed, 2232 insertions(+) create mode 100644 openfin/index.d.ts create mode 100644 openfin/openfin-tests.ts create mode 100644 openfin/tsconfig.json create mode 100644 openfin/tslint.json diff --git a/openfin/index.d.ts b/openfin/index.d.ts new file mode 100644 index 0000000000..97c5b2d2c1 --- /dev/null +++ b/openfin/index.d.ts @@ -0,0 +1,1493 @@ +// Type definitions for OpenFin API 15.0 +// Project: https://openfin.co/ +// Definitions by: Chris Barker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// based on v6.49.15.18 +// see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean + + +/** + * JavaScript API + * The JavaScript API allows you to create an HTML/JavaScript application that has access to the native windowing environment, can communicate with other applications and has access to sandboxed system-level features. + * + * API Ready + * When using the OpenFin API, it is important to ensure that it has been fully loaded before making any API calls. To verify that the API is in fact ready, be sure to make any API calls either from within the fin.desktop.main() method or explicitly after it has returned. This avoids the situation of trying to access methods that are not yet fully injected. + * + * Overview + * When running within the OpenFin Runtime your web applications have access to the "fin" namespace and all the modules within the API without the need to include additional source files. You can treat the "fin" namespace as you would the "window", "navigator" or "document" objects. + **/ +declare namespace fin { + const desktop: OpenFinDesktop; + + interface OpenFinDesktop { + main(f: () => any): void; + Application: OpenFinApplication; + ExternalApp: OpenFinExternalApplication; + InterApplicationBus: OpenFinInterApplicationBus; + Notification: OpenFinNotification; + System: OpenFinSystem; + Window: OpenFinWindow; + } + + /** + * Application + * An object representing an application.Allows the developer to create, execute, show / close an application as well as listen to application events. + */ + interface OpenFinApplication { + /** + * Creates a new Application. + * An object representing an application. Allows the developer to create, execute, show/close an application as well as listen to application events. + */ + new (options: ApplicationOptions, callback?: (successObj: { httpResponseCode: number }) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinApplication; + /** + * Returns an Application object that represents an existing application. + */ + getCurrent(): OpenFinApplication; + /** + * Returns an Application object that represents an existing application. + */ + wrap(uuid: string): OpenFinApplication; + /** + * Returns an instance of the main Window of the application + */ + getWindow(): OpenFinWindow; + /** + * Registers an event listener on the specified event. + */ + addEventListener(type: OpenFinApplicationEventType, listener: (event: ApplicationBaseEvent | TrayIconClickedEvent | WindowEvent | WindowAlertRequestedEvent | WindowAuthRequested | WindowNavigationRejectedEvent | WindowEndLoadEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the application and any child windows created by the application. + */ + close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of wrapped fin.desktop.Windows for each of the application’s child windows. + */ + getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows. + */ + getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest. + */ + getManifest(callback?: (manifest: any) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves UUID of the application that launches this application. Invokes the error callback if the application was created from a manifest. + */ + getParentUuid(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves current configuration of application's shortcuts. + */ + getShortcuts(callback?: (config: ShortCutConfig) => void, errorCallback?: (reason: string) => void): void; + /** + * Determines if the application is currently running. + */ + isRunning(callback?: (running: boolean) => void, errorCallback?: (reason: string) => void): void; + /** + * Passes in custom data that will be relayed to the RVM + */ + registerCustomData(data: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener(type: OpenFinApplicationEventType, previouslyRegisteredListener: (event: ApplicationBaseEvent | TrayIconClickedEvent | WindowEvent | WindowAlertRequestedEvent | WindowAuthRequested | WindowNavigationRejectedEvent | WindowEndLoadEvent) => any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes the application’s icon from the tray. + */ + removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Restarts the application. + */ + restart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Runs the application. When the application is created, run must be called. + */ + run(callback?: (successObj: SuccessObj) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * Tells the rvm to relaunch the main application once upon a complete shutdown + */ + scheduleRestart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets new shortcut configuration for current application. Application has to be launched with a manifest and has to have shortcut configuration (icon url, name, etc.) in its manifest to be able to change shortcut states. + */ + setShortcuts(config: ShortCutConfig, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Adds a customizable icon in the system tray and notifies the application when clicked. + */ + setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the application by terminating its process. + */ + terminate(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Waits for a hanging application. This method can be called in response to an application "not-responding" to allow the application to continue and to generate another "not-responding" message after a certain period of time. + */ + wait(callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface ShortCutConfig { + /** + * application has a shortcut on the desktop + */ + desktop?: boolean; + /** + * application has no shortcut in the start menu + */ + startMenu?: boolean; + /** + * application will be launched on system startup + */ + systemStartup?: boolean; + } + + interface SuccessObj { + httpResponseCode: number; + } + + interface NetworkErrorInfo extends ErrorInfo { + networkErrorCode: number; + } + + interface ErrorInfo { + stack: string; + message: string; + } + + interface ApplicationOptions { + url?: string; + uuid?: string; + name?: string; + mainWindowOptions?: WindowOptions; + } + + interface WindowOptions { + /** + * Enable keyboard shortcuts for devtools and zoom. Default: false for both. + */ + accelerator?: { + devtools?: boolean, + zoom?: boolean + }; + /** + * A flag to always position the window at the top of the window stack. Default: false. + */ + alwaysOnTop?: boolean; + /** + * A flag to automatically show the Window when it is created. Default: false. + */ + autoShow?: boolean; + /** + * A flag to show the context menu when right-clicking on a window. Gives access to the Developer Console for the Window. Default: true + */ + contextMenu?: boolean; + /** + * This defines and applies rounded corners for a frameless window. Default for both width and height: 0. + */ + cornerRounding?: { + width?: number; + height?: number; + }; + /** + * A field that the user can attach serializable data to to be ferried around with the window options. Default: ''. + */ + customData?: any; + /** + * Specifies that the window will be positioned in the center of the primary monitor when loaded for the first time on a machine. When the window corresponding to that id is loaded again, the position from before the window was closed is used. This option overrides defaultLeft and defaultTop. Default: false. + */ + defaultCentered?: boolean; + /** + * The default height of the window. Specifies the height of the window when loaded for the first time on a machine. When the window corresponding to that id is loaded again, the height is taken to be the last height of the window before it was closed. Default: 500. + */ + defaultHeight?: number; + /** + * The default left position of the window. Specifies the position of the left of the window when loaded for the first time on a machine. When the window corresponding to that id is loaded again, the value of left is taken to be the last value before the window was closed. Default: 100. + */ + defaultWidth?: number; + /** + * The default top position of the window. Specifies the position of the top of the window when loaded for the first time on a machine. When the window corresponding to that id is loaded again, the value of top is taken to be the last value before the window was closed. Default: 100. + */ + defaultTop?: number; + /** + * The default width of the window. Specifies the width of the window when loaded for the first time on a machine. When the window corresponding to that id is loaded again, the width is taken to be the last width of the window before it was closed. Default: 800. + */ + defaultLeft?: number; + /** + * A flag to show the frame. Default: true. + */ + frame?: boolean; + /** + * A flag to allow a window to be hidden when the close button is clicked.Default: false. + */ + hideOnClose?: boolean; + /** + * A URL for the icon to be shown in the window title bar and the taskbar.Default: The parent application's applicationIcon. + */ + icon?: string; + /** + * The maximum height of a window.Will default to the OS defined value if set to - 1. Default: -1. + */ + maxHeight?: number; + /** + * A flag that lets the window be maximized.Default: true. + */ + maximizable?: boolean; + /** + * The maximum width of a window.Will default to the OS defined value if set to - 1. Default: -1. + */ + maxWidth?: number; + /** + * The minimum height of a window.Default: 0. + */ + minHeight?: number; + /** + * A flag that lets the window be minimized.Default: true. + */ + minimizable?: boolean; + /** + * The minimum width of a window.Default: 0. + */ + minWidth?: number; + /** + * The name for the window which must be unique within the context of the invoking Application. + */ + name?: string; + /** + * A flag that specifies how transparent the window will be.This value is clamped between 0.0 and 1.0.Default: 1.0. + */ + opacity?: number; + /** + * A flag to drop to allow the user to resize the window.Default: true. + */ + resizable?: boolean; + /** + * Defines a region in pixels that will respond to user mouse interaction for resizing a frameless window. + */ + resizeRegion?: { + /** + * The size in pixels (Default: 2), + */ + size?: number; + /** + * The size in pixels of an additional + * square resizable region located at the + * bottom right corner of a + * frameless window. (Default: 4) + */ + bottomRightCorner?: number; + }; + /** + * A flag to show the Window's icon in the taskbar. Default: true. + */ + showTaskbarIcon?: boolean; + /** + * A flag to cache the location of the window or not. Default: true. + */ + saveWindowState?: boolean; + /** + * Specify a taskbar group for the window. Default: app's uuid. + */ + taskbarIconGroup?: string; + /** + * A string that sets the window to be "minimized", "maximized", or "normal" on creation. Default: "normal". + */ + state?: string; + /** + * The URL of the window. Default: "about:blank". + */ + url?: string; + /** + * When set to false, the window will render before the "load" event is fired on the content's window. Caution, when false you will see an initial empty white window. Default: true. + */ + waitForPageLoad?: boolean; + } + + /** + * Clipboard + * Clipboard API allows reading and writting to the clipboard in multiple formats. + */ + interface OpenFinClipboard { + /** + * Reads available formats for the clipboard type + */ + availableFormats(type: string | null, callback?: (formats: string[]) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Reads available formats for the clipboard type + */ + readHtml(type: string | null, callback?: (html: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Read the content of the clipboard as Rtf + */ + readRtf(type: string | null, callback?: (rtf: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Read the content of the clipboard as plain text + */ + readText(type: string | null, callback?: (text: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard + */ + write(data: any, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as Html + */ + writeHtml(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as Rtf + */ + writeRtf(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as plain text + */ + writeText(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + /** + * ExternalApplication + * An object representing an application. Allows the developer to create, execute, show and close an application, as well as listen to application events. + */ + interface OpenFinExternalApplication { + /** + * Returns an External Application object that represents an existing external application. + */ + wrap(uuid: string): OpenFinExternalApplication; + /** + * Registers an event listener on the specified event. + */ + addEventListener(type: OpenFinExternalApplicationEventType, listener: () => void, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener(type: OpenFinExternalApplicationEventType, listener: () => void, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + /** + * InterApplicationBus + * A messaging bus that allows for pub/sub messaging between different applications. + */ + interface OpenFinInterApplicationBus { + /** + * Adds a listener that gets called when applications subscribe to the current application's messages. + */ + addSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Adds a listener that gets called when applications unsubscribe to the current application's messages. + */ + addUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Removes a previously registered subscribe listener. + */ + removeSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Removes a previously registered unsubscribe listener. + */ + removeUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Publishes a message to all applications running on OpenFin Runtime that are subscribed to the specified topic. + */ + publish(topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sends a message to a specific application on a specific topic. + */ + send(destinationUuid: string, name: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + send(destinationUuid: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Subscribes to messages from the specified application on the specified topic. If the subscription is for a uuid, [name], topic combination that has already been published to upon subscription you will receive the last 20 missed messages in the order they were published. + */ + subscribe(senderUuid: string, name: string, topic: string, listener: (message: any, uuid: string, name: string) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + subscribe(senderUuid: string, topic: string, listener: (message: any, uuid: string, name: string) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Unsubscribes to messages from the specified application on the specified topic. + */ + unsubscribe(senderUuid: string, name: string, topic: string, listener: (message: any, uuid: string, name: string) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + unsubscribe(senderUuid: string, topic: string, listener: (message: any, uuid: string, name: string) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + /** + * Notification + * Notification represents a window on OpenFin Runtime which is shown briefly to the user on the bottom-right corner of the primary monitor. A notification is typically used to alert the user of some important event which requires his or her attention. Notifications are a child or your application that are controlled by the runtime. + */ + interface OpenFinNotification { + /** + * + */ + new (options: NotificationOptions, callback?: () => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinNotification; + /** + * Gets an instance of the current notification. For use within a notification window to close the window or send a message back to its parent application. + */ + getCurrent(): OpenFinNotification; + /** + * Closes the notification. + */ + close(callback?: () => void): void; + /** + * Sends a message to the notification. + */ + sendMessage(message: any, callback?: () => void): void; + /** + * Sends a message from the notification to the application that created the notification. The message is handled by the notification's onMessage callback. + */ + sendMessageToApplication(message: any, callback?: () => void): void; + } + + interface NotificationOptions { + /** + * A boolean that will force dismissal even if the mouse is hovering over the notification + */ + ignoreMouseOver?: boolean; + /** + * A message of any primitive or composite-primitive type to be passed to the notification upon creation. + */ + message?: any; + /** + * The timeout for displaying a notification.Can be in milliseconds or "never". + */ + duration?: number | "never"; + /** + * The url of the notification + */ + url?: string; + /** + * A function that is called when a notification is clicked. + */ + onClick?(callback: () => void): void; + /** + * Invoked when the notification is closed via .close() method on the created notification instance or the by the notification itself via fin.desktop.Notification.getCurrent().close(). NOTE: this is not invoked when the notification is dismissed via a swipe. For the swipe dismissal callback see onDismiss + */ + onClose?(callback: () => void): void; + /** + * Invoked when a the notification is dismissed by swiping it off the screen to the right. NOTE: this is no fired on a programmatic close. + */ + onDismiss?(callback: () => void): void; + /** + * A function that is called when an error occurs.The reason for the error is passed as an argument. + */ + onError?(errorCallback: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * The onMessage function will respond to messages sent from notification.sendMessageToApplication.The function is passed the message, which can be of any primitive or composite-primitive type. + */ + onMessage?(callback: (message: any) => void): void; + /** + * A function that is called when a notification is shown. + */ + onShow?(callback: (successObj: SuccessObj) => void): void; + } + + /** + * System + * An object representing the core of OpenFin Runtime. Allows the developer to perform system-level actions, such as accessing logs, viewing processes, clearing the cache and exiting the runtime. + */ + interface OpenFinSystem { + /** + * + */ + Clipboard: OpenFinClipboard; + /** + * Registers an event listener on the specified event. + */ + addEventListener(type: OpenFinSystemEventType, listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Clears cached data containing window state/positions, application resource files (images, HTML, JavaScript files), cookies, and items stored in the Local Storage. + */ + clearCache(options: CacheOptions, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Clears all cached data when OpenFin Runtime exits. + */ + deleteCacheOnExit(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Downloads the given application asset + */ + downloadAsset(assetObj: AppAssetInfo, progressListener?: (progress: { downloadedBytes: number, totalBytes: number }) => void, callback?: (successObj: { path: string }) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * Exits the Runtime. + */ + exit(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data for all applications. + */ + getAllApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data for all external applications. + */ + getAllExternalApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + */ + getAllWindows(callback?: (windowInfoList: WindowDetails[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the command line argument string that started OpenFin Runtime. + */ + getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the configuration object that started the OpenFin Runtime. + */ + getDeviceId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the value of a given environment variable on the computer on which the runtime is installed. + */ + getEnvironmentVariable(envVar: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the contents of the log with the specified filename. + */ + getLog(logFileName: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array containing information for each log file. + */ + getLogList(callback?: (logInfoList: LogInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an object that contains data about the about the monitor setup of the computer that the runtime is running on. + */ + getMonitorInfo(callback?: (monitorInfo: MonitorInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the mouse in virtual screen coordinates (left, top). + */ + getMousePosition(callback?: (mousePosition: VirtualScreenCoordinates) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of all of the runtime processes that are currently running. Each element in the array is an object containing the uuid and the name of the application to which the process belongs. + */ + getProcessList(callback?: (processInfoList: ProcessInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the Proxy settings. + */ + getProxySettings(callback?: (proxy: ProxyInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns information about the running RVM in an object. + */ + getRvmInfo(callback?: (rvmInfo: RvmInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the version of the runtime. The version contains the major, minor, build and revision numbers. + */ + getVersion(callback?: (version: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Runs an executable or batch file. + */ + launchExternalProcess(options: ExternalProcessLaunchInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + /** + * Writes the passed message into both the log file and the console. + */ + log(level: "debug" | "info" | "warn" | "error", message: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Monitors a running process. + */ + monitorExternalProcess(options: ExternalProcessInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + /** + * Opens the passed URL in the default web browser. + */ + openUrlWithBrowser(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * This function call will register a unique id and produce a token. The token can be used to broker an external connection. + */ + registerExternalConnection(uuid: string, callback?: (detail: { + /** + * this will be unique each time + */ + token: string; + /** + * "remote-connection-uuid" + */ + uuid: string; + }) => void, errorCallback?: (reason: string) => void): void; + /** + * Removes the process entry for the passed UUID obtained from a prior call of fin.desktop.System.launchExternalProcess(). + */ + releaseExternalProcess(processUuid: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener(type: OpenFinSystemEventType, listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the Chrome Developer Tools for the specified window. + */ + showDeveloperTools(uuid: string, name: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Attempt to close an external process. The process will be terminated if it has not closed after the elapsed timeout in milliseconds. + */ + terminateExternalProcess(processUuid: string, timeout: number, killTree: boolean, callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, errorCallback?: (reason: string) => void): void; + terminateExternalProcess(processUuid: string, timeout: number, callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, errorCallback?: (reason: string) => void): void; + /** + * Update the OpenFin Runtime Proxy settings. + */ + updateProxySettings(type: string, address: string, port: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + + } + + interface CacheOptions { + cache?: boolean; + cookies?: boolean; + localStorage?: boolean; + appcache?: boolean; + userData?: boolean; + } + + interface AppAssetInfo { + src?: string; + alias?: string; + version?: string; + target?: string; + args?: string; + } + + interface ApplicationInfo { + /** + * true when the application is running. + */ + isRunning?: boolean; + /** + * uuid of the application. + */ + uuid?: string; + /** + * uuid of the application that launches this application. + */ + parentUuid?: string; + } + + interface WindowDetails { + uuid?: string; + mainWindow?: WindowInfo; + childWindows?: WindowInfo[]; + } + + interface WindowInfo { + /** + * name of the child window + */ + name?: string; + /** + * top-most coordinate of the child window + */ + top?: number; + /** + * right-most coordinate of the child window + */ + right?: number; + /** + * bottom-most coordinate of the child window + */ + bottom?: number; + /** + * left-most coordinate of the child window + */ + left?: number; + } + + interface LogInfo { + /** + * the filename of the log + */ + name?: string; + /** + * the size of the log in bytes + */ + size?: number; + /** + * the unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)" + */ + date?: string; + } + + interface ProcessInfo { + /** + * the percentage of total CPU usage + */ + cpuUsage?: number; + /** + * the application name + */ + name?: string; + /** + * the current nonpaged pool usage in bytes + */ + nonPagedPoolUsage?: number; + /** + * the number of page faults + */ + pageFaultCount?: number; + /** + * the current paged pool usage in bytes + */ + pagedPoolUsage?: number; + /** + * the total amount of memory in bytes that the memory manager has committed + */ + pagefileUsage?: number; + /** + * the peak nonpaged pool usage in bytes + */ + peakNonPagedPoolUsage?: number; + /** + * the peak paged pool usage in bytes + */ + peakPagedPoolUsage?: number; + /** + * the peak value in bytes of pagefileUsage during the lifetime of this process + */ + peakPagefileUsage?: number; + /** + * the peak working set size in bytes + */ + peakWorkingSetSize?: number; + /** + * the native process identifier + */ + processId?: number; + /** + * the application UUID + */ + uuid?: string; + /** + * the current working set size (both shared and private data) in bytes + */ + workingSetSize?: number; + } + + interface ProxyInfo { + /** + * the configured Proxy Address + */ + proxyAddress?: string; + /** + * the configured Proxy port + */ + proxyPort?: number; + /** + * Proxy Type + */ + type?: string; + } + + interface RvmInfo { + version?: string; + "start-time"?: string; + } + + interface ExternalProcessLaunchInfo { + path?: string; + /** + * Additionally note that the executable found in the zip file specified in appAssets + * will default to the one mentioned by appAssets.target + * If the the path below refers to a specific path it will override this default + */ + alias?: string; + /** + * When using alias; if no arguments are passed then the arguments (if any) + * are taken from the 'app.json' file, from the 'args' parameter + * of the 'appAssets' Object with the relevant 'alias'. + * If 'arguments' is passed as a parameter it takes precedence + * over any 'args' set in the 'app.json'. + */ + arguments?: string; + listener?: (result: { + /** + * "Exited" Or "released" on a call to releaseExternalProcess + */ + topic?: string; + /** + * The mapped UUID which identifies the launched process + */ + uuid?: string; + /* + * Process exit code + */ + exitCode?: number; + }) => void; + certificate?: CertificationInfo; + } + + interface CertificationInfo { + /** + * A hex string with or without spaces + */ + serial?: string; + /** + * An internally tokenized and comma delimited string allowing partial or full checks of the subject fields + */ + subject?: string; + /** + * A hex string with or without spaces + */ + publickey?: string; + /** + * A hex string with or without spaces + */ + thumbprint?: string; + /** + * A boolean indicating that the certificate is trusted and not revoked + */ + trusted?: boolean; + } + + interface ExternalProcessInfo { + pid?: number; + listener?: (result: { + /** + * "Exited" Or "released" on a call to releaseExternalProcess + */ + topic?: string; + /** + * The mapped UUID which identifies the launched process + */ + uuid?: string; + /* + * Process exit code + */ + exitCode?: number; + }) => void; + } + + /** + * Window + * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. The new window appears in the same process as the parent window. + */ + interface OpenFinWindow { + /** + * Class: Window + * + * new Window(options, callbackopt, errorCallbackopt) + * + * Creates a new OpenFin Window + * + * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. The new window appears in the same process as the parent window. + * @param {any} options - The options of the window + * @param {Function} [callback] - Called if the window creation was successful + * @param {number} [callback.successObj] - httpResponseCode + */ + new (options: WindowOptions, callback?: (successObj: { httpResponseCode: number }) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinWindow; + /** + * Name of window + */ + name: string; + /** + * Returns an instance of the current window. + * @returns {OpenFinWindow} Current window + */ + getCurrent(): OpenFinWindow; + /** + * Returns the native JavaScript "window" object for the window. This method can only be used by the parent application or the window itself, otherwise it will return undefined. The same Single-Origin-Policy (SOP) rules apply for child windows created by window.open(url) in that the contents of the window object are only accessible if the URL has the same origin as the invoking window. See example below. Also, will not work with fin.desktop.Window objects created with fin.desktop.Window.wrap(). + * @returns {Window} Native window + */ + getNativeWindow(): Window; + /** + * Gets the parent application. + * @returns {OpenFinApplication} Parent application + */ + getParentApplication(): OpenFinApplication; + /** + * Gets the parent window. + */ + getParentWindow(): OpenFinWindow; + /** + * Returns a Window object that wraps an existing window. + */ + wrap(appUuid: string, windowName: string): OpenFinWindow; + /** + * Registers an event listener on the specified event. + */ + addEventListener(type: OpenFinWindowEventType, listener: (event: WindowBaseEvent | WindowAuthRequestedEvent | WindowBoundsEvent | WindowExternalProcessStartedEvent | WindowExternalProcessExited | WindowGroupChangedEvent | WindowHiddenEvent | Window_NavigationRejectedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Performs the specified window transitions + */ + animate(transitions: AnimationTransition, options: AnimationOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void; + /** + * Provides credentials to authentication requests + */ + authenticate(userName: string, password: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes focus from the window. + */ + blur(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Brings the window to the front of the OpenFin window stack. + */ + bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the window. + * @param {force} Close will be prevented from closing when force is false and ‘close-requested’ has been subscribed to for application’s main window. + */ + close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Prevents a user from changing a window's size/position when using the window's frame. + * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. + * 'disabled-frame-bounds-changed' is generated after a user move/size operation. + * The events provide the bounds that would have been applied if the frame was enabled. + * 'frame-disabled' is generated when an enabled frame becomes disabled. + */ + disableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Re-enables user changes to a window's size/position when using the window's frame. + * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. + * 'disabled-frame-bounds-changed' is generated after a user move/size operation. + * The events provide the bounds that would have been applied if the frame was enabled. + * 'frame-enabled' is generated when a disabled frame has becomes enabled. + */ + enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Flashes the window’s frame and taskbar icon until the window is activated. + */ + flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Gives focus to the window. + */ + focus(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current bounds (top, left, width, height) of the window. + */ + getBounds(callback?: (bounds: WindowBounds) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this window. If a window is not in a group an empty array is returned. Please note that calling window is included in the result array. + */ + getGroup(callback?: (group: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current settings of the window. + */ + getOptions(callback?: (options: WindowOptions) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets a base64 encoded PNG snapshot of the window. + */ + getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current state ("minimized", "maximized", or "restored") of the window. + */ + getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the zoom level of the window. + */ + getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void; + /** + * Hides the window. + */ + hide(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Determines if the window is currently showing. + */ + isShowing(callback?: (showing: boolean) => void, errorCallback?: (reason: string) => void): void; + /** + * Joins the same window group as the specified window. + */ + joinGroup(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Leaves the current window group so that the window can be move independently of those in the group. + */ + leaveGroup(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Maximizes the window. + */ + maximize(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Merges the instance's window group with the same window group as the specified window + */ + mergeGroups(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Minimizes the window. + */ + minimize(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Moves the window by a specified amount. + */ + moveBy(deltaLeft: number, deltaTop: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Moves the window to a specified location. + */ + moveTo(left: number, top: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener(type: OpenFinWindowEventType, listener: (event: WindowBaseEvent | WindowAuthRequestedEvent | WindowBoundsEvent | WindowExternalProcessStartedEvent | WindowExternalProcessExited | WindowGroupChangedEvent | WindowHiddenEvent | Window_NavigationRejectedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Resizes the window by a specified amount. + */ + resizeBy(deltaWidth: number, deltaHeight: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Resizes the window by a specified amount. + */ + resizeTo(width: number, height: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Restores the window to its normal state (i.e., unminimized, unmaximized). + */ + restore(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Will bring the window to the front of the entire stack and give it focus. + */ + setAsForeground(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the window's size and position + */ + setBounds(left: number, top: number, width: number, height: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the zoom level of the window. + */ + setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the window if it is hidden. + * @param {force} Show will be prevented from closing when force is false and ‘show-requested’ has been subscribed to for application’s main window. + */ + show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the window if it is hidden at the specified location. If the toggle parameter is set to true, the window will alternate between showing and hiding. + */ + showAt(left: number, top: number, force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Stops the taskbar icon from flashing. + */ + stopFlashing(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Updates the window using the passed options + */ + updateOptions(options: WindowOptions, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface ApplicationBaseEvent { + topic: string; + type: OpenFinApplicationEventType; + uuid: string; + } + + interface TrayIconClickedEvent extends ApplicationBaseEvent { + button: number; // 0 for left, 1 for middle, 2 for right + monitorInfo: MonitorInfo; + x: number; // the cursor x coordinate + y: number; // the cursor y coordinate + } + + interface WindowEvent extends ApplicationBaseEvent { + name: string; + } + + interface WindowAlertRequestedEvent extends WindowEvent { + message: string; + url: string; + } + + interface WindowAuthRequested extends WindowEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; + } + + interface WindowNavigationRejectedEvent extends WindowEvent { + sourceName: string; + url: string; + } + + interface WindowEndLoadEvent extends WindowEvent { + documentName: string; + isMain: boolean; + } + + interface MonitorInfoChangedEvent extends MonitorInfo { + topic: "system"; + type: "monitor-info-changed"; + } + + interface MonitorInfo { + nonPrimaryMonitors: MonitorInfoDetail[]; + primaryMonitor: MonitorInfoDetail; + reason: string; + taskbar: { + edge: "left" | "right" | "top" | "bottom", + rect: MontiorCoordinates + }; + topic: "system"; + type: "monitor-info-changed"; + virtualScreen: MontiorCoordinates; + } + + interface MonitorInfoDetail { + availableRect: MontiorCoordinates; + deviceId: string; + displayDeviceActive: boolean; + monitorRect: MontiorCoordinates; + name: string; + } + + interface MontiorCoordinates { + bottom: number; + left: number; + right: number; + top: number; + } + + interface VirtualScreenCoordinates { + left: number; + top: number; + } + + interface SystemBaseEvent { + topic: string; + type: OpenFinSystemEventType; + uuid: string; + } + + interface DesktopIconClickedEvent { + mouse: { + /** + * the left virtual screen coordinate of the mouse + */ + left: number, + /** + * the top virtual screen coordinate of the mouse + */ + top: number + }; + /** + * the number of milliseconds that have elapsed since the system was started, + */ + tickCount: number; + topic: "system"; + type: "desktop-icon-clicked"; + } + + interface IdleStateChangedEvent { + /** + * How long in milliseconds since the user has been idle. + */ + elapsedTime: number; + /** + * true when the user is idle,false when the user has returned; + */ + isIdle: boolean; + topic: "system"; + type: "idle-state-changed"; + } + + interface WindowBaseEvent { + /** + * the name of the window + */ + name: string; + /** + * always window + */ + topic: "window"; + /** + * window event type + */ + type: OpenFinWindowEventType; + /** + * the UUID of the application the window belongs to + */ + uuid: string; + } + + interface WindowAuthRequestedEvent extends WindowBaseEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; + } + + interface WindowBoundsEvent extends WindowBaseEvent { + /** + * describes what kind of change occurred. + * 0 means a change in position. + * 1 means a change in size. + * 2 means a change in position and size. + */ + changeType: number; + /** + * true when pending changes have been applied to the window. + */ + deferred: boolean; + /** + * the new height of the window. + */ + height: number; + /** + * the left-most coordinate of the window. + */ + left: number; + /** + * the top-most coordinate of the window. + */ + top: number; + /** + * + */ + type: "bounds-changed" | "bounds-changing" | "disabled-frame-bounds-changed" | "disabled-frame-bounds-changing"; + /** + * the new width of the window. + */ + width: number; + } + + interface WindowExternalProcessStartedEvent extends WindowBaseEvent { + /** + * the process handle uuid + */ + processUuid: string; + type: "external-process-started"; + } + + interface WindowExternalProcessExited extends WindowBaseEvent { + /** + * the process exit code + */ + exitCode: number; + /** + * the process handle uuid + */ + processUuid: string; + type: "external-process-exited"; + } + + interface WindowGroupChangedEvent extends WindowBaseEvent { + /** + * Which group array the window that the event listener was registered on is included in: + * 'source' The window is included in sourceGroup. + * 'target' The window is included in targetGroup. + * 'nothing' The window is not included in sourceGroup nor targetGroup. + */ + memberOf: "source" | "target" | "nothing"; + /** + * The reason this event was triggered. + * 'leave' A window has left the group due to a leave or merge with group. + * 'join' A window has joined the group. + * 'merge' Two groups have been merged together. + * 'disband' There are no other windows in the group. + */ + reason: "leave" | "join" | "merge" | "disband"; + /** + * All the windows in the group the sourceWindow originated from. + */ + sourceGroup: WindowOfGroupInfo[]; + /** + * The UUID of the application the sourceWindow belongs to The source window is the window in which (merge/join/leave)group(s) was called. + */ + sourceWindowAppUuid: string; + /** + * the name of the sourcewindow.The source window is the window in which(merge / join / leave) group(s) was called. + */ + sourceWindowName: string; + /** + * All the windows in the group the targetWindow orginated from + */ + targetGroup: WindowOfGroupInfo[]; + /** + * The UUID of the application the targetWindow belongs to. The target window is the window that was passed into (merge/join) group(s). + */ + targetWindowAppUuid: string; + /** + * The name of the targetWindow. The target window is the window that was passed into (merge/join) group(s). + */ + targetWindowName: string; + type: "group-changed"; + } + + interface WindowOfGroupInfo { + /** + * The UUID of the application this window entry belongs to. + */ + appUuid: string; + /** + * The name of this window entry. + */ + windowName: string; + } + + interface WindowHiddenEvent extends WindowBaseEvent { + /** + * What action prompted the close. + * The reasons are: "hide", "hide-on-close" + */ + reason: "hide" | "hide-on-close"; + type: "hidden"; + } + + interface Window_NavigationRejectedEvent { + name: string; + /** + * source of navigation window name + */ + sourceName: string; + topic: "navigation-rejected"; + /** + * Url that was not reached "http://blocked-content.url" + */ + url: string; + /** + * the UUID of the application the window belongs to. + */ + uuid: string; + } + + interface AnimationTransition { + opacity?: { + /** + * This value is clamped from 0.0 to 1.0 + */ + opacity?: number; + /** + * The total time in milliseconds this transition should take. + */ + duration?: number; + /** + * Treat 'opacity' as absolute or as a delta. Defaults to false. + */ + relative?: boolean; + }; + position?: { + /** + * Defaults to the window's current left position in virtual screen coordinates. + */ + left?: number; + /** + * Defaults to the window's current top position in virtual screen coordinates. + */ + top?: number; + /** + * The total time in milliseconds this transition should take. + */ + duration?: number; + /** + * Treat 'left' and 'top' as absolute or as deltas. Defaults to false. + */ + relative?: boolean; + }; + size?: { + /** + * Optional if height is present. Defaults to the window's current width. + */ + width?: number; + /** + * Optional if width is present. Defaults to the window's current height. + */ + height?: number; + /** + * The total time in milliseconds this transition should take. + */ + duration?: number; + /** + * Treat 'width' and 'height' as absolute or as deltas. Defaults to false. + */ + relative?: boolean; + }; + } + + interface AnimationOptions { + /** + * This option interrupts the current animation. When false it pushes this animation onto the end of the animation queue. + */ + interrupt?: boolean; + /** + * Transition effect. Defaults to 'ease-in-out'. + */ + tween?: OpenFinTweenType; + } + + interface WindowBounds { + /** + * the height of the window. + */ + height?: number; + /** + * left-most coordinate of the window. + */ + left?: number; + /** + * top-most coordinate of the window. + */ + top?: number; + /** + * the width of the window. + */ + width?: number; + } + + interface SessionChangedEvent { + /** + * the action that triggered this event: + */ + reason: "lock" + | "unlock" + | "remote-connect" + | "remote-disconnect" + | "unknown"; + topic: "system"; + type: "session-changed"; + } + + type OpenFinTweenType = "linear" + | "ease-in" + | "ease-out" + | "ease-in-out" + | "ease-in-quad" + | "ease-out-quad" + | "ease-in-out-quad" + | "ease-in-cubic" + | "ease-out-cubic" + | "ease-in-out-cubic" + | "ease-out-bounce" + | "ease-in-back" + | "ease-out-back" + | "ease-in-out-back" + | "ease-in-elastic" + | "ease-out-elastic" + | "ease-in-out-elastic"; + + type OpenFinApplicationEventType = "closed" + | "connected" + | "crashed" + | "initialized" + | "manifest-changed" + | "not-responding" + | "out-of-memory" + | "responding" + | "run-requested" + | "started" + | "tray-icon-clicked" + | "window-alert-requested" + | "window-auth-requested" + | "window-closed" + | "window-created" + | "window-end-load" + | "window-navigation-rejected" + | "window-show-requested" + | "window-start-load"; + + type OpenFinExternalApplicationEventType = "connected" + | "disconnected"; + + type OpenFinSystemEventType = "application-closed" + | "application-crashed" + | "application-created" + | "application-started" + | "desktop-icon-clicked" + | "idle-state-changed" + | "monitor-info-changed" + | "session-changed"; + + type OpenFinWindowEventType = "auth-requested" + | "blurred" + | "bounds-changed" + | "bounds-changing" + | "close-requested" + | "closed" + | "disabled-frame-bounds-changed" + | "disabled-frame-bounds-changing" + | "embedded" + | "external-process-exited" + | "external-process-started" + | "focused" + | "frame-disabled" + | "frame-enabled" + | "group-changed" + | "hidden" + | "initialized" + | "maximized" + | "minimized" + | "navigation-rejected" + | "restored" + | "show-requested" + | "shown"; + + type OpenFinAnchor = "top-left" + | "top-right" + | "bottom-left" + | "bottom-right"; +} \ No newline at end of file diff --git a/openfin/openfin-tests.ts b/openfin/openfin-tests.ts new file mode 100644 index 0000000000..7aa2930089 --- /dev/null +++ b/openfin/openfin-tests.ts @@ -0,0 +1,718 @@ + +function test_application() { + let application: fin.OpenFinApplication; + // constructor + application = new fin.desktop.Application({ + url: "application.html", + uuid: "74BED629-2D8E-4141-8582-73E364BDFA74", + name: "Application Name", + mainWindowOptions: { + defaultHeight: 600, + defaultWidth: 800, + defaultTop: 300, + defaultLeft: 300, + autoShow: true + } + }, function (successObj) { + console.log("Application successfully created, HTTP response code:", successObj); + application.run(); + }, function (error) { + console.log("Error creating application:", error); + }); + // getCurrent + application = fin.desktop.Application.getCurrent(); + // wrap + application = fin.desktop.Application.wrap("454C7F31-A915-4EA2-83F2-CFA655453C52"); + // getWindow + application.getWindow(); + // addEventListener + application.addEventListener("closed", function (event) { + console.log("The application has closed"); + }, function () { + console.log("The registration was successful"); + }, function (reason) { + console.log("failure: " + reason); + }); + // close + application.close(); + // getChildWindows + application.getChildWindows(function (children) { + children.forEach(function (childWindow) { + console.log("Showing child: " + childWindow.name); + childWindow.show(); + }); + }); + // getGroups + application.getGroups(function (allGroups) { + console.log("There are a total of " + allGroups.length + " groups."); + + var groupCounter = 1; + allGroups.forEach(function (windowGroup) { + console.log("Group " + groupCounter + " contains " + + windowGroup.length + " windows."); + ++groupCounter; + }); + }); + // getManifest + application.getManifest(function (manifest) { + console.log("Application manifest:"); + console.log(manifest); + }); + // getParentUuid + application.getParentUuid(function (parentUuid) { + console.log("UUID of parent application:"); + console.log(parentUuid); + }); + // getShortcuts + application.getShortcuts(function (config) { + console.log("Desktop shortcut is enabled: ", config.desktop); + console.log("Start Menu shortcut is enabled: ", config.startMenu); + console.log("System Startup shortcut is enabled: ", config.systemStartup); + }); + // isRunning + application.isRunning(function (running) { + console.log("the application is", running ? "running" : "not running"); + }); + // registerCustomData + application.registerCustomData({ + someData: "this is custom" + }, function () { + console.log("You will not read this."); + }, function (err) { + console.log("failure:", err); + }); + // removeEventListener + let previousCallback = function (event: fin.WindowEvent) { }; + application.removeEventListener("closed", previousCallback, function () { + console.log("The unregistration was successful"); + }, function (err) { + console.log("failure:", err); + }); + // removeTrayIcon + application.removeTrayIcon(function () { + console.log("Removed the tray icon."); + }, function (err) { + console.log("failure:", err); + }); + // restart + application.restart(function () { + console.log("You will not read this."); + }, function (err) { + console.log("failure:", err); + }); + // schedule restart + application.scheduleRestart(function () { + console.log("You will not read this."); + }, function (err) { + console.log("failure:", err); + }); + // setShortcuts + application.setShortcuts({ + desktop: true, + startMenu: false, + systemStartup: true + }, function () { + console.log("Successfully set new shortcut states"); + }, function (error) { + console.log("Failed to set new shortcut states. Error: ", error); + }); + // setTrayIcon + application.setTrayIcon("https://developer.openf.in/download/openfin.png", function (clickInfo) { + console.log("The mouse has clicked at (" + clickInfo.x + "," + clickInfo.y + ")"); + }); + // terminate + application.terminate(); + // wait + application.addEventListener("not-responding", function () { + console.log("waiting for hung application"); + application.wait(); + }); +} + +function test_external_application() { + let externalApp: fin.OpenFinExternalApplication; + // wrap + externalApp = fin.desktop.ExternalApp.wrap('my-uuid'); + // addEventListener + externalApp.addEventListener('connected', () => { + console.log('external app connected'); + }, () => { + console.log('The registration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + // removeEventListener + let previousCallback = function () { }; + externalApp.removeEventListener('connected', previousCallback, () => { + console.log('The unregistration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); +} + +function test_inter_application_bus() { + // addSubscribeListener + fin.desktop.InterApplicationBus.addSubscribeListener(function (uuid, topic, name) { + console.log("The application " + uuid + " has subscribed to " + topic); + }); + // addUnsubscribeListener + fin.desktop.InterApplicationBus.addUnsubscribeListener(function (uuid, topic, name) { + console.log("The application " + uuid + " has unsubscribed to " + topic); + }); + // removeSubscribeListener + let aRegisteredListener = function (uuid: string, topic: string, name: string) { }; + fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); + // removeUnsubscribeListener + fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); + // publish + fin.desktop.InterApplicationBus.publish("a topic", { + field1: "value1", + field2: "value2" + }); + // send + fin.desktop.InterApplicationBus.send("an application's uuid", "a topic", { + field1: "value1", + field2: "value2" + }); + // subscribe + fin.desktop.InterApplicationBus.subscribe("*", "a topic", function (message, uuid, name) { + console.log("The application " + uuid + " sent this message: " + message); + }); + // unsubscribe + let aRegisteredMessageListener = function (message: any, senderUuid: string) { + console.log(message, senderUuid); + }; + fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); +} + +function test_notification() { + let notification: fin.OpenFinNotification; + // getCurrent + notification = fin.desktop.Notification.getCurrent(); + // close + notification.close(); + // sendMessage + notification = new fin.desktop.Notification({ + duration: 10, + url: "http://localhost:5000/Account/Register", + message: "Hello", + onShow: () => { }, + //onClose: () => { }, + onDismiss: () => { }, + //onClick: () => { }, + onMessage: () => { }, + onError: () => { } + }); + // sendMessageToApplication + notification.sendMessageToApplication("some message"); +} + +function test_system() { + // addEventListener + fin.desktop.System.addEventListener('monitor-info-changed', function (event) { + console.log("The monitor information has changed to: ", event); + }, function () { + console.log("The registration was successful"); + }, function (err) { + console.log("failure: " + err); + }); + // clearCache + fin.desktop.System.clearCache({ + cache: true, + cookies: true, + localStorage: true, + appcache: true, + userData: true + }); + // deleteCacheOnExit + fin.desktop.System.deleteCacheOnExit(function () { + console.log("successful"); + }, function (err) { + console.log("failure: " + err); + }); + // downloadAsset + let dirAppAsset = { + 'src': 'http://local:8000/dir.zip', + 'alias': 'dirApp', + 'version': '1.23.24', + 'target': 'dir.bat', + 'args': '' + }; + fin.desktop.System.downloadAsset(dirAppAsset, progress => { + let downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + console.log(`Downloaded ${downloadedPercent}%`); + }, p => { + console.log(`Downlod complete, can be found on ${p.path}`); + //lets launch our application asset. + //launchDirApp(); + }, (reason, err) => { + console.log(reason, err); + }); + // exit + fin.desktop.System.exit(function () { + console.log("successful"); + }, function (err) { + console.log("failure: " + err); + }); + // getAllApplications + fin.desktop.System.getAllApplications(function (applicationInfoList) { + applicationInfoList.forEach(function (applicationInfo) { + console.log("Showing information for application with uuid: " + + applicationInfo.uuid); + console.log("isRunning: ", applicationInfo.isRunning); + }); + }); + // getAllExternalApplications + fin.desktop.System.getAllExternalApplications(externalAppsInfoList => { + externalAppsInfoList.forEach(appInfo => { + console.log(`External app connected to the runtime with UUID ${appInfo.uuid}`); + }); + }); + // getAllWindows + fin.desktop.System.getAllWindows(function (windowInfoList) { + windowInfoList.forEach(function (windowInfo) { + console.log("Showing information for application with uuid: ", windowInfo.uuid); + console.log("Main window: ", windowInfo.mainWindow); + console.log("Child windows: ", windowInfo.childWindows); + }); + }); + // getCommandLineArguments + fin.desktop.System.getCommandLineArguments(function (args) { + console.log("The command line arguments are " + args); + }); + // getDeviceId + fin.desktop.System.getDeviceId(function (id) { + console.log("The id of the device is: " + id); + }); + // getEnvironmentVariable + fin.desktop.System.getEnvironmentVariable("APPDATA", function (variable) { + console.log("this is the APPDATA value", variable); + }); + // getLog + fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', function (log) { + console.log(log); + }); + // getLogList + fin.desktop.System.getLogList(function (logList) { + logList.forEach(function (logInfo) { + console.log("The filename of the log is " + + logInfo.name + ", the size is " + + logInfo.size + ", and the date of creation is " + + logInfo.date); + }); + }); + // getMonitorInfo + fin.desktop.System.getMonitorInfo(function (monitorInfo) { + console.log("This object contains information about all monitors: ", monitorInfo); + }); + // getMousePosition + fin.desktop.System.getMousePosition(function (mousePosition) { + console.log("The mouse is located at left: " + mousePosition.left + ", top: " + mousePosition.top); + }); + // getProcessList + fin.desktop.System.getProcessList(function (list) { + list.forEach(function (process) { + console.log("UUID: " + process.uuid + ", Application Name: " + process.name); + }); + }); + // getProxySettings + fin.desktop.System.getProxySettings(function (proxy) { + console.log(proxy); + }); + // getRvmInfo + fin.desktop.System.getRvmInfo(function (rvmInfoObject) { + console.log("RVM version:", rvmInfoObject.version); + console.log("RVM has been running since:", rvmInfoObject["start-time"]); + }, function (err) { + console.log("Failed to get rvm info, error message:", err); + }); + // getVersion + fin.desktop.System.getVersion(function (version) { + console.log("The version is " + version); + }); + // launchExternalProcess + fin.desktop.System.launchExternalProcess({ + path: "notepad", + arguments: "", + listener: function (result) { + console.log('the exit code', result.exitCode); + } + }, function (payload) { + console.log('Success:', payload.uuid); + }, function (error) { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + //Additionally note that the executable found in the zip file specified in appAssets + //will default to the one mentioned by appAssets.target + //If the the path below refers to a specific path it will override this default + alias: "myApp", + listener: function (result) { + console.log('the exit code', result.exitCode); + } + }, function (payload) { + console.log('Success:', payload.uuid); + }, function (error) { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + alias: "myApp", + arguments: "e f g", + listener: function (result) { + console.log('the exit code', result.exitCode); + } + }, function (payload) { + console.log('Success:', payload.uuid); + }, function (error) { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + path: "C:\Users\ExampleUser\AppData\Local\OpenFin\OpenFinRVM.exe", + arguments: "--version", + certificate: { + trusted: true, + subject: 'O=OpenFin INC., L=New York, S=NY, C=US', + thumbprint: '‎3c a5 28 19 83 05 fe 69 88 e6 8f 4b 3a af c5 c5 1b 07 80 5b' + }, + listener: function (result) { + console.log('the exit code', result.exitCode); + } + }, function (payload) { + console.log('Success:', payload.uuid); + }, function (error) { + console.log('Error:', error); + }); + // log + fin.desktop.System.log("info", "An example log message", function () { + console.log("message successfully logged"); + }, function (err) { + console.log(err); + }); + // monitorExternalProcess + fin.desktop.System.monitorExternalProcess({ + pid: 2508, + listener: function (result) { + console.log('the exit code', result.exitCode); + } + }, function (payload) { + console.log("The process is now being monitored: ", payload.uuid); + }, function (error) { + console.log("Error:", error); + }); + // openUrlWithBrowser + fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", function () { + console.log("successful"); + }, function (err) { + console.log("failure: " + err); + }); + // registerExternalConnection + fin.desktop.System.registerExternalConnection("remote-connection-uuid", function () { + console.log(arguments); + }); + // releaseExternalProcess + fin.desktop.System.launchExternalProcess({ + path: "notepad", + arguments: "", + listener: function (result) { + console.log("The exit code", result.exitCode); + } + }, function (result) { + console.log("Result UUID is " + result.uuid); + + //release it. + fin.desktop.System.releaseExternalProcess(result.uuid, function () { + console.log("Process has been unmapped!"); + }, function (reason) { + console.log("failure: " + reason); + }); + }); + // removeEventListener + let aRegisteredListener = (event: fin.SystemBaseEvent) => { }; + fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, function () { + console.log("successful"); + }, function (err) { + console.log("failure: " + err); + }); + // showDeveloperTools + fin.desktop.System.showDeveloperTools("uuid", "name", function () { + console.log("successful"); + }, function (err) { + console.log("failure: " + err); + }); + // terminateExternalProcess + fin.desktop.System.launchExternalProcess({ + // notepad is in the system’s PATH + path: "notepad", + arguments: "", + listener: function (result) { + console.log("The exit code", result.exitCode); + } + }, function (result) { + console.log("Result UUID is " + result.uuid); + + // Attempt to close the process. Terminate after 4 seconds if it + // has not done so. + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, function (info) { + console.log("Termination result " + info.result); + }, function (reason) { + console.log("failure: " + reason); + }); + }); + // updateProxySettings + fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, function () { + console.log('success'); + }, function (err) { + console.log(err); + }); +} + +function test_system_clipboard() { + // availableFormats + fin.desktop.System.Clipboard.availableFormats(null, formats => { + formats.forEach(format => console.log(`The format ${format} is available to read`)); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readHtml + fin.desktop.System.Clipboard.readHtml(null, html => { + console.log(`This is the html from the clipboard: ${html}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readRtf + fin.desktop.System.Clipboard.readRtf(null, rtf => { + console.log(`This is the rtf from the clipboard: ${rtf}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readText + fin.desktop.System.Clipboard.readText(null, text => { + console.log(`This is the text from the clipboard: ${text}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // write + fin.desktop.System.Clipboard.write({ + text: 'Hello Text!', + html: '

Hello Html

', + rtf: 'Hello Rtf' + }, null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeHtml + fin.desktop.System.Clipboard.writeHtml('

Hello World

', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeRtf + fin.desktop.System.Clipboard.writeRtf('Hello World!', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeText + fin.desktop.System.Clipboard.writeText('Hello World', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); +} + +function test_window() { + let finWindow: fin.OpenFinWindow; + // constructor + finWindow = new fin.desktop.Window({ + name: "childWindow", + url: "child.html", + defaultWidth: 320, + defaultHeight: 320, + defaultTop: 10, + defaultLeft: 300, + frame: false, + resizable: false, + state: "normal" + }, function () { + var _win = finWindow.getNativeWindow(); + _win.addEventListener("DOMContentLoaded", function () { finWindow.show(); }); + }, function (error) { + console.log("Error creating window:", error); + }); + // getCurrent + finWindow = fin.desktop.Window.getCurrent(); + // getNativeWindow + let nativeWindow: Window; + nativeWindow = finWindow.getNativeWindow(); + // getParentApplication + let parentApp: fin.OpenFinApplication; + parentApp = finWindow.getParentApplication(); + // getParentWindow + let parentFinWindow: fin.OpenFinWindow; + parentFinWindow = finWindow.getParentWindow(); + // wrap + finWindow = fin.desktop.Window.wrap("uuid", "name"); + // addEventListener + finWindow.addEventListener("bounds-changed", function (event) { + console.log("The window has been moved or resized"); + }, function () { + console.log("The registration was successful"); + }, function (reason) { + console.log("failure:" + reason); + }); + // animate + finWindow.animate({ + opacity: { + opacity: 0.15, + duration: 1000 + }, + position: { + left: 10, + top: 10, + duration: 3000 + } + }, { + interrupt: false + }, function (evt) { + // Callback will only fire after both "opacity" and "position" have finished animating. + }); + // authenticate + finWindow.addEventListener('auth-requested', evt => { + finWindow.authenticate('userName', 'P@assw0rd', () => { }, (reason, err) => { + console.log("failure:", err); + }); + }); + // blur + finWindow.blur(); + // bringToFront + finWindow.bringToFront(); + // close + finWindow.close(); + // disableFrame + finWindow.disableFrame(); + // enableFrame + finWindow.enableFrame(); + // flash + finWindow.flash(); + // focus + finWindow.focus(); + // getBounds + finWindow.getBounds(function (bounds) { + console.log("top: " + bounds.top + + "left: " + bounds.left + + "height: " + bounds.height + + "width: " + bounds.width); + }); + // getOptions + finWindow.getOptions(function (options) { + console.log(options); + }); + // getSnapshot + finWindow.getSnapshot(function (base64Snapshot) { + console.log("data:image/png;base64," + base64Snapshot); + }); + // getState + finWindow.getState(function (state) { + console.log("state: " + state); + }); + // getZoomLevel + finWindow.getZoomLevel(function (level) { + console.log("zoom level: " + level); + }, function (error) { + console.log('error:', error); + }); + // hide + finWindow.hide(); + // isShowing + finWindow.isShowing(function (showing) { + console.log("the window is " + (showing ? "showing" : "hidden")); + }); + // joinGroup + let secondWindow = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "secondWindow", + autoShow: true + }, function () { + // When mainWindow moves or is moved, secondWindow moves by the same amount + secondWindow.joinGroup(finWindow); + }); + // leaveGroup + secondWindow = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "secondWindow", + autoShow: true + }, function () { + // When finWindow moves or is moved, secondWindow moves by the same amount + secondWindow.joinGroup(finWindow, function () { + //once we are in the group, lets leave it. + secondWindow.leaveGroup(); + }); + }); + // maximize + finWindow.maximize(); + // mergeGroups + { + let finWindowOne = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowOne", + autoShow: true + }); + let finWindowTwo = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowTwo", + autoShow: true + }); + let finWindowThree = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowThree", + autoShow: true + }); + let finWindowFour = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowFour", + autoShow: true + }); + // When finWindowOne moves or is moved, finWindowTwo moves by the same amount + finWindowOne.joinGroup(finWindowTwo); + // When finWindowThree moves or is moved, finWindowFour moves by the same amount + finWindowThree.joinGroup(finWindowFour); + // finWindowOne, finWindowTwo, finWindowThree, and finWindowFour now move together in the same group + finWindowOne.mergeGroups(finWindowThree); + } + // minimize + finWindow.minimize(); + // moveBy + finWindow.moveBy(10, 10); + // moveTo + finWindow.moveTo(100, 200); + // removeEventListener + let aRegisteredListener = (event: fin.WindowBaseEvent) => { }; + finWindow.removeEventListener("bounds-changed", aRegisteredListener); + // resizeBy + finWindow.resizeBy(10, 10, "top-right"); + // resizeTo + finWindow.resizeTo(10, 10, "top-right"); + // restore + finWindow.restore(); + // setAsForeground + finWindow.setAsForeground(); + // setBounds + finWindow.setBounds(100, 200, 400, 400); + // setZoomLevel + finWindow.setZoomLevel(10); + // show + finWindow.show(); + // showAt + finWindow.showAt(10, 10, false); + // stopFlashing + finWindow.stopFlashing(); + // updateOptions + finWindow.updateOptions({ + frame: false, + maxWidth: 500 + }); +} \ No newline at end of file diff --git a/openfin/tsconfig.json b/openfin/tsconfig.json new file mode 100644 index 0000000000..8785bdb90f --- /dev/null +++ b/openfin/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "openfin-tests.ts" + ] +} diff --git a/openfin/tslint.json b/openfin/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/openfin/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 1414eeea60afe42e45b2d3a50f8dc72b126ee5fb Mon Sep 17 00:00:00 2001 From: Margus Lamp Date: Tue, 17 Jan 2017 23:13:58 +0200 Subject: [PATCH 21/72] Elasticsearch client.deleteByQuery params update for 5.x (#14053) * Elasticsearch client.deleteByQuery params update for 5.x * Header fix * Added _source, _sourceExclude, _sourceInclude * df and from are optional parameters --- elasticsearch/index.d.ts | 47 ++++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/elasticsearch/index.d.ts b/elasticsearch/index.d.ts index 6558c94f2f..faeab9eb38 100644 --- a/elasticsearch/index.d.ts +++ b/elasticsearch/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for elasticsearch 5.0 // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski , Margus Lamp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { @@ -143,6 +143,7 @@ declare module Elasticsearch { export type VersionType = "internal" | "external" | "external_gte" | "force"; export type ExpandWildcards = "open" | "closed" | "none" | "all"; export type DefaultOperator = "AND" | "OR"; + export type Conflicts = "abort" | "proceed"; export interface BulkIndexDocumentsParams extends GenericParams { waitForActiveShards?: string; @@ -234,16 +235,40 @@ declare module Elasticsearch { } export interface DeleteDocumentByQueryParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: string | string[] | boolean; + scroll?: string; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: string | string[] | boolean; version?: number; - versionType?: VersionType; - index: string; - type: string; - id: string; + requestCache?: boolean; + refresh?: Refresh; + timeout?: TimeSpan; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index?: string; + type?: string; } export interface DeleteDocumentByQueryResponse { @@ -710,7 +735,7 @@ declare module Elasticsearch { from?: number; ignoreUnavailable?: boolean; allowNoIndices?: boolean; - conflicts?: "abort" | "proceed"; + conflicts?: Conflicts; expandWildcards?: ExpandWildcards; lenient?: boolean; lowercaseExpandedTerms?: boolean; From f6aa10df3061a587c289fd037801557f1eaf8a31 Mon Sep 17 00:00:00 2001 From: denisname Date: Tue, 17 Jan 2017 22:22:05 +0100 Subject: [PATCH 22/72] Add shared space and editor path variable (#14048) Add Shared Space interface with top and bottom properties. Add `CKEDITOR_BASEPATH` global variable. --- ckeditor/ckeditor-tests.ts | 18 ++++++++++++++++++ ckeditor/index.d.ts | 12 +++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts index 3ec9b64fd5..289e97168a 100644 --- a/ckeditor/ckeditor-tests.ts +++ b/ckeditor/ckeditor-tests.ts @@ -389,3 +389,21 @@ function test_htmlWriter() { writer.lineBreak(); writer.setRules('img', {breakBeforeOpen: true, breakAfterOpen: true}); } + +function test_sharedSpace() { + CKEDITOR.inline('content', { + removePlugins: 'maximize,resize', + sharedSpaces: { + top: 'someElementId', + bottom: document.getElementById('anotherId') + } + }); + + CKEDITOR.inline('content', { + sharedSpaces: { } + }); +} + +function test_specifying_editor_path() { + window.CKEDITOR_BASEPATH = '/ckeditor/'; +} diff --git a/ckeditor/index.d.ts b/ckeditor/index.d.ts index 271ca0b678..55a748e4c5 100644 --- a/ckeditor/index.d.ts +++ b/ckeditor/index.d.ts @@ -5,6 +5,10 @@ // WORK-IN-PROGRESS: Any contribution support welcomed. // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1827 for more informations. +interface Window { + CKEDITOR_BASEPATH: string; +} + declare namespace CKEDITOR { // Config options @@ -784,7 +788,7 @@ declare namespace CKEDITOR { scayt_uiTabs?: string; scayt_userDictionaryName?: string; - sharedSpaces?: Object; + sharedSpaces?: CKEDITOR.sharedSpace; shiftEnterMode?: number; skin?: string; smiley_columns?: number; @@ -834,6 +838,12 @@ declare namespace CKEDITOR { } + interface sharedSpace { + top?: string | HTMLElement; + bottom?: string | HTMLElement; + } + + interface style { } From a661f615b6429ccac3d396382545af5ae6220e62 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 17 Jan 2017 13:23:49 -0800 Subject: [PATCH 23/72] Fix rrule: when imported, it uses `import { RRule } from "rrule";`, not `import RRule = require("rrule");`. (#14051) * Fix rrule: when imported, it uses `import { RRule } from "rrule";`, not `import RRule = require("rrule");`. * Support both CommonJS and AMD loading by exporting two different ways. --- rrule/index.d.ts | 20 +++++++++++++++----- rrule/test/commonJs.ts | 2 ++ rrule/test/global.ts | 1 + rrule/{rrule-tests.ts => test/rrule.ts} | 2 +- rrule/tsconfig.json | 4 +++- rrule/tslint.json | 1 + 6 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 rrule/test/commonJs.ts create mode 100644 rrule/test/global.ts rename rrule/{rrule-tests.ts => test/rrule.ts} (97%) create mode 100644 rrule/tslint.json diff --git a/rrule/index.d.ts b/rrule/index.d.ts index 436af1c2cf..b09d47ff2a 100644 --- a/rrule/index.d.ts +++ b/rrule/index.d.ts @@ -1,10 +1,20 @@ -// Type definitions for rrule 2.1.0 +// Type definitions for rrule 2.1 // Project: https://github.com/jkbrzt/rrule // Definitions by: James Bracy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'rrule' { - export = RRule; +export as namespace RRule; + +/** + * Use `import rrule = require("rrule")` for AMD and `import { RRule } from "rrule"` for CommonJS loading. + */ +export = RRule; + +// For CommonJS it must be imported as `require("rrule").RRule`. +import RRuleAlias = RRule; +declare module "rrule" { + export type RRule = RRuleAlias; + export const RRule: typeof RRuleAlias; } declare namespace RRule { @@ -17,7 +27,7 @@ declare namespace RRule { freq: RRule.Frequency; dtstart?: Date; interval?: number; - wkst?: number | Weekday + wkst?: number | Weekday; count?: number; until?: Date; bysetpos?: number | number[]; @@ -25,7 +35,7 @@ declare namespace RRule { bymonthday?: number | number[]; byyearday?: number | number[]; byweekno?: number | number[]; - byweekday?: Weekday | Weekday[] | number | number[]; + byweekday?: Weekday | Weekday[] | number | number[]; byhour?: number | number[]; byminute?: number | number[]; bysecond?: number | number[]; diff --git a/rrule/test/commonJs.ts b/rrule/test/commonJs.ts new file mode 100644 index 0000000000..e6a2c86dac --- /dev/null +++ b/rrule/test/commonJs.ts @@ -0,0 +1,2 @@ +import { RRule } from "rrule"; +let rule: RRule = new RRule({ freq: RRule.WEEKLY }); diff --git a/rrule/test/global.ts b/rrule/test/global.ts new file mode 100644 index 0000000000..869d407e98 --- /dev/null +++ b/rrule/test/global.ts @@ -0,0 +1 @@ +let rule: RRule = new RRule({ freq: RRule.WEEKLY }); diff --git a/rrule/rrule-tests.ts b/rrule/test/rrule.ts similarity index 97% rename from rrule/rrule-tests.ts rename to rrule/test/rrule.ts index 64cfe72282..733a8546db 100644 --- a/rrule/rrule-tests.ts +++ b/rrule/test/rrule.ts @@ -1,4 +1,4 @@ -import * as RRule from 'rrule'; +import RRule = require('rrule'); // Create a rule: let rule: RRule = new RRule({ diff --git a/rrule/tsconfig.json b/rrule/tsconfig.json index 15b5cb19f9..50a83efddf 100644 --- a/rrule/tsconfig.json +++ b/rrule/tsconfig.json @@ -15,6 +15,8 @@ }, "files": [ "index.d.ts", - "rrule-tests.ts" + "test/rrule.ts", + "test/commonJs.ts", + "test/global.ts" ] } \ No newline at end of file diff --git a/rrule/tslint.json b/rrule/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/rrule/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file From 00221afddf7073bcbdf88a3e2485dde5ae00df78 Mon Sep 17 00:00:00 2001 From: Vlad Rindevich Date: Wed, 18 Jan 2017 00:25:14 +0300 Subject: [PATCH 24/72] Add node-libpq typings (#14044) * add type definition for package: libpq * style(libpq): change indent size to 4 white-spaces * test(libpq): add tests for libpq * test(libpq): more tests for libpq * chore(libpq): create project by 'npm run new-project' script * test(libpq): fix call signature * fix(libpq): update in accordance with test information * doc(libpq): improve documentation in accordance with typedoc * fix(libpq): connection callback argument type should be Error, not string * doc(libpq): stylize documentation * feat(libpq): add exporting inner interfaces --- libpq/index.d.ts | 428 ++++++++++++++++++++++ libpq/libpq-tests.ts | 828 +++++++++++++++++++++++++++++++++++++++++++ libpq/tsconfig.json | 20 ++ libpq/tslint.json | 1 + 4 files changed, 1277 insertions(+) create mode 100644 libpq/index.d.ts create mode 100644 libpq/libpq-tests.ts create mode 100644 libpq/tsconfig.json create mode 100644 libpq/tslint.json diff --git a/libpq/index.d.ts b/libpq/index.d.ts new file mode 100644 index 0000000000..df2135046a --- /dev/null +++ b/libpq/index.d.ts @@ -0,0 +1,428 @@ +// Type definitions for libpq 1.8 +// Project: https://github.com/brianc/node-libpq#readme +// Definitions by: Vlad Rindevich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import {EventEmitter} from 'events'; +import {Buffer} from 'buffer'; + +declare namespace Libpq { + export interface NotifyMsg { + relname: string; + extra: string; + be_pid: number; + } + + export interface ResultError { + severity: string; + sqlState: string; + messagePrimary: string; + messageDetail?: string; + messageHint?: string; + statementPosition?: string; + internalPosition?: string; + internalQuery?: string; + context?: string; + schemaName?: string; + tableName?: string; + dataTypeName?: string; + constraintName?: string; + sourceFile: string; + sourceLine: string; + sourceFunction: string; + } +} + +declare class Libpq extends EventEmitter { + + /** + * Current connection state. + */ + connected: boolean; + + /** + * Issues a request to cancel the currently executing query on this instance of libpq. + * + * @returns {(boolean|string)} true if the cancel request was sent; a string error message if + * the cancel request failed for any reason. The string will + * contain the error message provided by libpq. + */ + cancel(): true|string; + + /** + * Manually frees the memory associated with a PGresult pointer. Generally this is called + * for you, but if you absolutely want to free the pointer yourself, you can. + */ + clear(): void; + + /** + * @returns {string} the status string associated with a result. Something akin to INSERT 3 0 + * if you inserted 3 rows. + */ + cmdStatus(): string; + + /** + * @returns {string} the number of tuples (rows) affected by the command. Even though this is a + * number, it is returned as a string to mirror libpq's behavior. + */ + cmdTuples(): string; + + /** + * (async) Connects to a PostgreSQL backend server process. + * + * This function actually calls the PQconnectdb blocking connection method in a background + * thread within node's internal thread-pool. There is a way to do non-blocking network I/O + * for some of the connecting with libpq directly, but it still blocks when your local file + * system looking for config files, SSL certificates, .pgpass file, and doing possible dns + * resolution. Because of this, the best way to get fully non-blocking is to juse use + * libuv_queue_work and let node do it's magic and so that's what I do. This function does + * not block. + * + * @param {string} connectParams an optional string + * @param {Function} callback mandatory. It is called when the connection has successfully been + * established. + */ + connect(connectParams: string, callback: (err?: Error) => void): void; + connect(callback: (err?: Error) => void): void; + + /** + * (sync) Attempts to connect to a PostgreSQL server. BLOCKS until it either succeedes, or + * fails. If it fails it will throw an exception. + * + * @param {string} connectionParams an optional string + */ + connectSync(connectionParams?: string): void; + + /** + * Reads waiting data from the socket. If the socket is not readable and you call this it will + * block so be careful and only call it within the readable callback for the most part. + * + * @returns {boolean} true if data was read; false if there was an error. You can access + * error details with [[Libpq.errorMessage]]. + */ + consumeInput(): boolean + + /** + * Retrieves the last error message from the connection. This is intended to be used after most + * functions which return an error code to get more detailed error information about the + * connection. You can also check this before issuing queries to see if your connection has + * been lost. + * + * @returns {string} + */ + errorMessage(): string; + + /** + * Exact copy of the PQescapeIdentifier function within libpq. Requires an established + * connection but does not perform any I/O. + * + * @param {string} input + */ + escapeIdentifier(input: string): string; + + /** + * Exact copy of the PQescapeLiteral function within libpq. Requires an established connection + * but does not perform any I/O. + * + * @param {string} input + */ + escapeLiteral(input: string): string; + + /** + * (sync) Sends a command to the backend and blocks until a result is received. + * + * @param {string} [commandText=""] a required string of the query. + */ + exec(commandText?: string): void; + + /** + * (sync) Sends a command and parameters to the backend and blocks until a result is received. + * + * @param {string} [commandText=""] a required string of the query. + * @param {Array.<(string|number)>} [parameters=[]] a required array of string values + * corresponding to each parameter in the + * commandText. + */ + execParams(commandText?: string, parameters?: Array): void; + + /** + * (sync) Sends a command to the server to execute a previously prepared statement. Blocks + * until the results are returned. + * + * @param {string} [statementName=""] a required string of the name of the prepared statement. + * @param {Array.<(string|number)>} [parameters=[]] the parameters to pass to the prepared + * statement. + */ + execPrepared(statementName?: string, parameters?: Array): void; + + /** + * Disconnects from the backend and cleans up all memory used by the libpq connection. + */ + finish(): void; + + /** + * Flushes buffered data to the socket. + * + * @returns {number} 1 if socket is not write-ready at which case you should call + * [[Libpq.writable]] with a callback and wait for the socket to be writable + * and then call [[Libpq.flush]] again; 0 if all data was flushed; -1 if + * there was an error. + */ + flush(): number; + + /** + * Retrieve the name of the field (column) at the given offset. Offset starts at 0. + * + * @param {number} fieldNumber + * @returns {string} + */ + fname(fieldNumber: number): string; + + /** + * Retrieve the Oid of the field (column) at the given offset. Offset starts at 0. + * + * @param {number} fieldNumber + * @returns {number} + */ + ftype(fieldNumber: number): number; + + /** + * After issuing a successfuly command like COPY table TO stdout gets copy data from the + * connection. + * + * @param {boolean} [async=false] a boolean. Pass false to block waiting for data from the + * backend. Defaults to false. + * + * @returns {Buffer|number} a node buffer if there is data available; 0 if the copy is still in + * progress (only if you have called [[Libpq.setNonBlocking]](true)); + * -1 if the copy is completed; -2 if there was an error. + */ + getCopyData(async?: boolean): Buffer|number; + + /** + * @param {number} tupleNumber + * @param {number} fieldNumber + * @returns {boolean} true if the value at the given offsets is actually null. Otherwise + * returns false. This is because [[Libpq.getvalue]] returns an empty + * string for both an actual empty string and for a null value. Weird, huh? + */ + getisnull(tupleNumber: number, fieldNumber: number): boolean; + + /** + * Parses received data from the server into a PGresult struct and sets a pointer internally to + * the connection object to this result. + * + * Warning: this function will block if libpq is waiting on async results to be returned from + * the server. Call [[Libpq.isBusy]] to determine if this command will block. + * + * @returns {boolean} true if libpq was able to read buffered data & parse a result object; + * false if there are no results waiting to be parsed. Generally doing async + * style queries you'll call this repeadedly until it returns false and then + * use the result accessor methods to pull results out of the current result + * set. + */ + getResult(): boolean; + + /** + * Retrieve the text value at a given tuple (row) and field (column) offset. Both offsets start + * at 0. A null value is returned as the empty string ''. + * + * @param {number} tupleNumber + * @param {number} [fieldNumber] + * @returns {string} + */ + getvalue(tupleNumber: number, fieldNumber?: number): string; + + /** + * @returns {boolean} true if calling [[Libpq.consumeInput]] would block waiting for more + * data; false if all data has been read from the socket. Once this returns false it is + * safe to call [[Libpq.getResult]]. + */ + isBusy(): boolean; + + /** + * @returns {boolean} true if non-blocking mode is enabled; false if disabled. + */ + isNonBlocking(): boolean; + + /** + * Retrieve the number of fields (columns) from the result. + * + * @returns {number} + */ + nfields(): number; + + /** + * Checks for NOTIFY messages that have come in. If any have been received they will be in the + * following format: + * + * @example ```ts + * + * var msg = { + * relname: 'name of channel', + * extra: 'message passed to notify command', + * be_pid: 130 + * } + * ``` + * + * @returns {Libpq.NotifyMsg} + */ + notifies(): Libpq.NotifyMsg; + + /** + * Retrieve the number of tuples (rows) from the result. + * + * @returns {number} + */ + ntuples(): number; + + /** + * After issuing a successful command like COPY table FROM stdin you can start putting buffers + * directly into the databse with this function. + * + * @param {Buffer} buffer a required node buffer of text data such as + * Buffer('column1\tcolumn2\n') + * + * @returns {number} 1 if sent succesfully; 0 if the command would block (only if you have + * called [[Libpq.setNonBlocking]](true)); -1 if there was an error sending + * the command. + */ + putCopyData(buffer: Buffer): number; + + /** + * Signals the backed your copy procedure is complete. If you pass errorMessage it will be sent + * to the backend and effectively cancel the copy operation. + * + * @param {string} [errorMessage] an optional string you can pass to cancel the copy operation. + * + * @returns {number} 1 if sent succesfully; 0 if the command would block (only if you have + * called [[Libpq.setNonBlocking]](true)); -1 if there was an error sending + * the command. + */ + putCopyEnd(errorMessage?: string): number; + + /** + * (sync) Sends a named statement to the server to be prepared for later execution. blocks + * until a result from the prepare operation is received. + * + * @param {string} [statementName=""] a required string of name of the statement to prepare. + * @param {string} [commandText=""] a required string of the query. + * @param {number} [nParams=0] a count of the number of parameters in the commandText. + */ + prepare(statementName?: string, commandText?: string, nParams?: number): void; + + /** + * Retrieves detailed error information from the current result object. Very similar to + * PQresultErrorField() except instead of passing a fieldCode and retrieving a single field, + * retrieves all fields from the error at once on a single object. The object returned is a + * simple hash, not an instance of an error object. + * + * If you wanted to access PG_DIAG_MESSAGE_DETAIL you would do the following: + * @example ```ts + * + * console.log(pq.errorFields().messageDetail); + * ``` + * @returns {Libpq.ResultError} + */ + resultErrorFields(): Libpq.ResultError; + + /** + * Retrieves the error message from the result. This will return null if the result does not + * have an error. + * + * @returns {string} + */ + resultErrorMessage(): string; + + /** + * @returns {string} either PGRES_COMMAND_OK or PGRES_FATAL_ERROR depending on the status of + * the last executed command. + */ + resultStatus(): string; + + /** + * (async) Sends a query to the server to be processed. + * + * @param {string} [commandText=""] a required string containing the query text. + * @returns {boolean} true if the command was sent succesfully or false if it failed to send. + */ + sendQuery(commandText?: string): boolean; + + /** + * (async) Sends a query and to the server to be processed. + * + * @param {string} [commandText=""] a required string containing the query text. + * @param {Array.<(string|number)>} [parameters=[]] an array of parameters as strings used in + * the parameterized query. + * @returns {boolean} true if the command was sent succesfully or false if it failed to send. + */ + sendQueryParams(commandText?: string, parameters?: Array): boolean; + + /** + * (async) Sends a request to the backend to prepare a named statement with the given name. + * + * @param {string} [statementName=""] a required string of name of the statement to prepare. + * @param {string} [commandText=""] a required string of the query. + * @param {number} [nParams=0] a count of the number of parameters in the commandText. + * @returns {boolean} true if the command was sent succesfully or false if it failed to send. + */ + sendPrepare(statementName?: string, commandText?: string, nParams?: number): boolean; + + /** + * (async) Sends a request to execute a previously prepared statement. + * + * @param {string} [statementName=""] a required string of the name of the prepared statement. + * @param {string[]} [parameters=[]] the parameters to pass to the prepared statement. + * @returns {boolean} true if the command was sent succesfully or false if it failed to send. + */ + sendQueryPrepared(statementName?: string, parameters?: string[]): boolean; + + /** + * @returns the version of the connected PostgreSQL backend server as a number. + */ + serverVersion(): number; + + /** + * Toggle the socket blocking on write. + * + * @param {boolean} [nonBlocking] true to set the connection to use non-blocking writes, false to + * use blocking writes. + * + * @returns {boolean} true if the socket's state was succesfully toggled, false if there was + * an error. + */ + setNonBlocking(nonBlocking?: boolean): boolean; + + /** + * @returns {number} an int representing the file descriptor for the socket used internally by + * the connection. + */ + socket(): number; + + /** + * This uses libuv to start a read watcher on the socket open to the backend. As soon as this + * socket becomes readable the pq instance will emit a readable event. It is up to you to call + * [[Libpq.consumeInput]] one or more times to clear this read notification or it will + * continue to emit read events over and over and over. The exact flow is outlined [here] under + * the documentation for PQisBusy. + */ + startReader(): void; + + /** + * Tells libuv to stop the read watcher on the connection socket. + */ + stopReader(): void; + + /** + * Call this to make sure the socket has flushed all data to the operating system. Once the + * socket is writable, your callback will be called. Usefully when using PQsetNonBlocking + * and PQflush for async writing. + * + * @param {Function} callback + */ + writable(callback: () => void): void; +} + +export = Libpq; diff --git a/libpq/libpq-tests.ts b/libpq/libpq-tests.ts new file mode 100644 index 0000000000..dda341a4bb --- /dev/null +++ b/libpq/libpq-tests.ts @@ -0,0 +1,828 @@ +/// +/// + +import {Buffer} from 'buffer'; +import * as assert from 'assert'; +import * as async from 'async'; +import * as PQ from 'libpq'; +import * as _ from 'lodash'; + +declare const ok: Function; + +const createTable = (pq: PQ) => { + pq.exec('CREATE TEMP TABLE test_data(name text, age int)'); + console.log(pq.resultErrorMessage()); + pq.exec("INSERT INTO test_data(name, age) VALUES ('brian', 32), ('aaron', 30), ('', null);") +}; + +const blink = (n: number, cb: Function) => { + const connections: PQ[] = []; + for (let i = 0; i < 30; i++) { + connections.push(new PQ()) + } + const connect = (con: PQ, cb: (err?: Error) => void) => { + con.connect(cb); + }; + async.each(connections, connect, ok(() => { + connections.forEach((con) => { + con.finish(); + }); + cb(); + })) +}; + +const queryText = "SELECT * FROM generate_series(1, 1000)"; + +const query = (pq: PQ, cb: Function) => { + const readError = (message?: string) => { + cleanup(); + return cb(new Error(message || pq.errorMessage())); + }; + + const onReadable = () => { + if (!pq.consumeInput()) { + return readError(); + } + + if (pq.isBusy()) { + return; + } + + pq.getResult(); + + if (pq.getResult()) { + return readError('Only one result at a time is accepted'); + } + cleanup(); + return cb(null, []) + }; + + const sent = pq.sendQuery(queryText); + if (!sent) return cb(new Error(pq.errorMessage())); + console.log('sent query'); + + const cleanup = () => { + pq.removeListener('readable', onReadable); + pq.stopReader(); + }; + + pq.on('readable', onReadable); + pq.startReader(); +}; + +describe('async connection', () => { + it('works', (done) => { + const pq = new PQ(); + assert(!pq.connected, 'should have connected set to falsy'); + pq.connect(err => { + assert.ifError(err); + pq.exec('SELECT NOW()'); + assert.equal(pq.ntuples(), 1); + done(); + }); + }); + + it('works with hard-coded connection parameters', (done) => { + const pq = new PQ(); + const conString = `host=${process.env.PGHOST || 'localhost'}`; + pq.connect(conString, done); + }); + + it('returns an error to the callback if connection fails', (done) => { + new PQ().connect('host=asldkfjasldkfjalskdfjasdf', err => { + assert(err, 'should have passed an error'); + done(); + }); + }); + + it('respects the active domain', (done) => { + const pq = new PQ(); + const domain = require('domain').create(); + domain.run(() => { + const activeDomain = process.domain; + assert(activeDomain, 'Should have an active domain'); + pq.connect(() => { + assert.strictEqual(process.domain, activeDomain, 'Active domain is lost'); + done(); + }); + }); + }); +}); + +const consume = (pq: PQ, cb: Function) => { + if (!pq.isBusy()) return cb(); + pq.startReader(); + const onReadable = () => { + assert(pq.consumeInput(), pq.errorMessage()); + if (pq.isBusy()) { + console.log('consuming a 2nd buffer of input later...'); + return; + } + pq.removeListener('readable', onReadable); + pq.stopReader(); + cb(); + }; + pq.on('readable', onReadable); +}; + +describe('async simple query', () => { + let pq: PQ; + + it('dispatches simple query', (done: Function) => { + assert(pq.setNonBlocking(true)); + pq.writable(() => { + const success = pq.sendQuery('SELECT 1'); + assert.strictEqual(pq.flush(), 0, 'Should have flushed all data to socket'); + assert(success, pq.errorMessage()); + consume(pq, () => { + assert.ifError(pq.errorMessage()); + assert(pq.getResult()); + assert.strictEqual(pq.getResult(), false); + assert.strictEqual(pq.ntuples(), 1); + assert.strictEqual(pq.getvalue(0, 0), '1'); + done(); + }); + }); + }); + + it('dispatches parameterized query', (done: Function) => { + const success = pq.sendQueryParams('SELECT $1::text as name', ['Brian']); + assert(success, pq.errorMessage()); + assert.strictEqual(pq.flush(), 0, 'Should have flushed query text & parameters'); + consume(pq, () => { + assert.ifError(pq.errorMessage()); + assert(pq.getResult()); + assert.strictEqual(pq.getResult(), false); + assert.strictEqual(pq.ntuples(), 1); + assert.equal(pq.getvalue(0, 0), 'Brian'); + done(); + }) + }); + + it('dispatches named query', (done: Function) => { + const statementName = 'async-get-name'; + const success = pq.sendPrepare(statementName, 'SELECT $1::text as name', 1); + assert(success, pq.errorMessage()); + assert.strictEqual(pq.flush(), 0, 'Should have flushed query text'); + consume(pq, () => { + assert.ifError(pq.errorMessage()); + + //first time there should be a result + assert(pq.getResult()); + + //call 'getResult' until it returns false indicating + //there is no more input to consume + assert.strictEqual(pq.getResult(), false); + + //since we only prepared a statement there should be + //0 tuples in the result + assert.equal(pq.ntuples(), 0); + + //now execute the previously prepared statement + const success = pq.sendQueryPrepared(statementName, ['Brian']); + assert(success, pq.errorMessage()); + assert.strictEqual(pq.flush(), 0, 'Should have flushed parameters'); + consume(pq, () => { + assert.ifError(pq.errorMessage()); + + //consume the result of the query execution + assert(pq.getResult()); + assert.equal(pq.ntuples(), 1); + assert.equal(pq.getvalue(0, 0), 'Brian'); + + //call 'getResult' again to ensure we're finished + assert.strictEqual(pq.getResult(), false); + done(); + }); + }); + }); +}); + +describe('cancel a request', () => { + it('works', (done) => { + const pq = new PQ(); + pq.connectSync(); + const sent = pq.sendQuery('pg_sleep(5000)'); + assert(sent, 'should have sent'); + const canceled = pq.cancel(); + assert.strictEqual(canceled, true, 'should have canceled'); + const hasResult = pq.getResult(); + assert(hasResult, 'should have a result'); + assert.equal(pq.resultStatus(), 'PGRES_FATAL_ERROR'); + assert.equal(pq.getResult(), false); + pq.exec('SELECT NOW()'); + done(); + }); +}); + +describe('Constructing multiple', () => { + it('works all at once', () => { + for (let i = 0; i < 1000; i++) { + const pq = new PQ(); + } + }); + + it('connects and disconnects each client', (done) => { + const connect = (n: number, cb: (err?: Error) => void) => { + const pq = new PQ(); + pq.connect(cb); + }; + async.times(30, connect, done); + }); +}); + +describe('COPY IN', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + it('check existing data assuptions', () => { + pq.exec('SELECT COUNT(*) FROM test_data'); + assert.equal(pq.getvalue(0, 0), 3); + }); + + it('copies data in', () => { + const success = pq.exec('COPY test_data FROM stdin'); + assert.equal(pq.resultStatus(), 'PGRES_COPY_IN'); + + const buffer = new Buffer("bob\t100\n", 'utf8'); + const res1 = pq.putCopyData(buffer); + assert.strictEqual(res1, 1); + + const res2 = pq.putCopyEnd(); + assert.strictEqual(res2, 1); + + while (pq.getResult()) { + } + + pq.exec('SELECT COUNT(*) FROM test_data'); + assert.equal(pq.getvalue(0, 0), 4); + }); + + it('can cancel copy data in', () => { + const success = pq.exec('COPY test_data FROM stdin'); + assert.equal(pq.resultStatus(), 'PGRES_COPY_IN'); + + const buffer = new Buffer("bob\t100\n", 'utf8'); + const res1 = pq.putCopyData(buffer); + assert.strictEqual(res1, 1); + + const res2 = pq.putCopyEnd('cancel!'); + assert.strictEqual(res2, 1); + + while (pq.getResult()) { + } + assert(pq.errorMessage()); + assert( + pq.errorMessage().includes('cancel!'), + `${pq.errorMessage()} should have contained "cancel!"` + ); + + pq.exec('SELECT COUNT(*) FROM test_data'); + assert.equal(pq.getvalue(0, 0), 4); + }); +}); + +describe('COPY OUT', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + const getRow = (pq: PQ, expected: string) => { + const result = pq.getCopyData(false); + assert(result instanceof Buffer, 'Result should be a buffer'); + assert.equal(result.toString('utf8'), expected); + }; + + it('copies data out', () => { + pq.exec('COPY test_data TO stdin'); + assert.equal(pq.resultStatus(), 'PGRES_COPY_OUT'); + getRow(pq, 'brian\t32\n'); + getRow(pq, 'aaron\t30\n'); + getRow(pq, '\t\\N\n'); + assert.strictEqual( pq.getCopyData(), -1); + }); +}); + +describe('without being connected', () => { + it('exec fails', () => { + const pq = new PQ(); + pq.exec(); + assert.equal(pq.resultStatus(), 'PGRES_FATAL_ERROR'); + assert(pq.errorMessage()); + }); + + it('fails on async query', () => { + const pq = new PQ(); + const success = pq.sendQuery('blah'); + assert.strictEqual(success, false); + assert.equal(pq.resultStatus(), 'PGRES_FATAL_ERROR'); + assert(pq.errorMessage()); + }); + + it('throws when reading while not connected', () => { + const pq = new PQ(); + assert.throws(() => { + pq.startReader(); + }); + }); + + it('throws when writing while not connected', () => { + const pq = new PQ(); + assert.throws(() => { + pq.writable(() => { + }); + }); + }); +}); + +describe('error info', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + describe('when there is no error', () => { + + it('everything is null', () => { + pq.exec('SELECT NOW()'); + assert(!pq.errorMessage(), pq.errorMessage()); + assert.equal(pq.ntuples(), 1); + assert(pq.resultErrorFields(), undefined); + }); + }); + + describe('when there is an error', () => { + it('sets all error codes', () => { + pq.exec('INSERT INTO test_data VALUES(1, NOW())'); + assert(pq.errorMessage()); + const err = pq.resultErrorFields(); + assert.notEqual(err, null); + assert.equal(err.severity, 'ERROR'); + assert.equal(err.sqlState, 42804); + assert.equal(err.messagePrimary, 'column "age" is of type integer but expression is of type timestamp with time zone'); + assert.equal(err.messageDetail, undefined); + assert.equal(err.messageHint, 'You will need to rewrite or cast the expression.'); + assert.equal(err.statementPosition, 33); + assert.equal(err.internalPosition, undefined); + assert.equal(err.internalQuery, undefined); + assert.equal(err.context, undefined); + assert.equal(err.schemaName, undefined); + assert.equal(err.tableName, undefined); + assert.equal(err.dataTypeName, undefined); + assert.equal(err.constraintName, undefined); + assert.equal(err.sourceFile, "parse_target.c"); + assert(parseInt(err.sourceLine)); + assert.equal(err.sourceFunction, "transformAssignedExpr"); + }); + }); +}); + +describe('escapeLiteral', () => { + it('fails to escape when the server is not connected', () => { + const pq = new PQ(); + const result = pq.escapeLiteral('test'); + assert.strictEqual(result, null); + assert(pq.errorMessage()); + }); + + it('escapes a simple string', () => { + const pq = new PQ(); + pq.connectSync(); + const result = pq.escapeLiteral('bang'); + assert.equal(result, "'bang'"); + }); + + it('escapes a bad string', () => { + const pq = new PQ(); + pq.connectSync(); + const result = pq.escapeLiteral("'; TRUNCATE TABLE blah;"); + assert.equal(result, "'''; TRUNCATE TABLE blah;'"); + }); +}); + +describe('escapeIdentifier', () => { + it('fails when the server is not connected', () => { + const pq = new PQ(); + const result = pq.escapeIdentifier('test'); + assert.strictEqual(result, null); + assert(pq.errorMessage()); + }); + + it('escapes a simple string', () => { + const pq = new PQ(); + pq.connectSync(); + const result = pq.escapeIdentifier('bang'); + assert.equal(result, '"bang"'); + }); +}); + +describe('connecting', () => { + it('works', () => { + const client = new PQ(); + client.connectSync(); + }); +}); + +describe('many connections', () => { + it('works', (done) => { + async.timesSeries(10, blink, done) + }) +}); + +describe('connectSync', () => { + it('works 50 times in a row', () => { + const pqs = _.times(50, () => new PQ()); + pqs.forEach((pq) => { + pq.connectSync(); + }); + pqs.forEach((pq) => { + pq.finish(); + }); + }); +}); + +describe('connect async', () => { + const total = 50; + it(`works ${total} times in a row`, (done) => { + const pqs = _.times(total, () => new PQ()); + + let count = 0; + const connect = (cb: Function) => { + pqs.forEach((pq) => { + pq.connect((err) => { + assert.ifError(err); + count++; + pq.startReader(); + if (count == total) { + cb(); + } + }); + }); + }; + connect(() => { + pqs.forEach((pq) => { + pq.stopReader(); + pq.finish(); + }); + done(); + }); + }); +}); + +describe('multiple queries', () => { + const pq = new PQ(); + + before((done) => { + pq.connect(done) + }); + + it('first query works', (done) => { + query(pq, done); + }); + + it('second query works', (done) => { + query(pq, done); + }); + + it('third query works', (done) => { + query(pq, done); + }); +}); + +describe('set & get non blocking', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + it('is initially set to false', () => { + assert.strictEqual(pq.isNonBlocking(), false); + }); + + it('can switch back and forth', () => { + assert.strictEqual(pq.setNonBlocking(true), true); + assert.strictEqual(pq.isNonBlocking(), true); + assert.strictEqual(pq.setNonBlocking(), true); + assert.strictEqual(pq.isNonBlocking(), false); + }); +}); + +describe('LISTEN/NOTIFY', () => { + let listener: PQ; + let notifier: PQ; + + before(() => { + listener = new PQ(); + notifier = new PQ(); + listener.connectSync(); + notifier.connectSync(); + }); + + it('works', () => { + notifier.exec("NOTIFY testing, 'My Payload'"); + let notice = listener.notifies(); + assert.equal(notice, null); + + listener.exec('LISTEN testing'); + notifier.exec("NOTIFY testing, 'My Second Payload'"); + listener.exec('SELECT NOW()'); + notice = listener.notifies(); + assert(notice, 'listener should have had a notification come in'); + assert.equal(notice.relname, 'testing', 'missing relname == testing'); + assert.equal(notice.extra, 'My Second Payload'); + assert(notice.be_pid); + }); + + after(() => { + listener.finish(); + notifier.finish(); + }); +}); + +describe('result accessors', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + before(() => { + pq.exec("INSERT INTO test_data(name, age) VALUES ('bob', 80) RETURNING *"); + assert(!pq.errorMessage()); + }); + + it('has ntuples', () => { + assert.strictEqual(pq.ntuples(), 1); + }); + + it('has cmdStatus', () => { + assert.equal(pq.cmdStatus(), 'INSERT 0 1'); + }); + + it('has command tuples', () => { + assert.strictEqual(pq.cmdTuples(), '1'); + }); +}); + +describe('Retrieve server version from connection', () => { + + it('return version number when connected', () => { + const pq = new PQ(); + pq.connectSync(); + const version = pq.serverVersion(); + assert.equal(typeof version, 'number'); + assert(version > 60000); + }); + + it('return zero when not connected', () => { + const pq = new PQ(); + const version = pq.serverVersion(); + assert.equal(typeof version, 'number'); + assert.equal(version, 0); + }); + +}); + +describe('getting socket', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + it('returns -1 when not connected', () => { + const pq = new PQ(); + assert.equal(pq.socket(), -1); + }); + + it('returns value when connected', () => { + assert(pq.socket() > 0); + }); +}); + +describe('connecting with bad credentials', () => { + it('throws an error', () => { + try { + new PQ().connectSync('asldkfjlasdf'); + } catch (e) { + assert.equal(e.toString().indexOf('connection pointer is NULL'), -1); + return; + } + + assert.fail(null, null, 'Should have thrown an exception', ''); + }); +}); + +describe('connecting with no credentials', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + }); + + it('is connected', () => { + assert(pq.connected, 'should have connected == true'); + }); + + after(() => { + pq.finish(); + assert(!pq.connected); + }); +}); + +describe('result checking', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + }); + + after(() => { + pq.finish(); + }); + + it('executes query', () => { + pq.exec('SELECT NOW() as my_col'); + assert.equal(pq.resultStatus(), 'PGRES_TUPLES_OK'); + }); + + it('has 1 tuple', () => { + assert.equal(pq.ntuples(), 1); + }); + + it('has 1 field', () => { + assert.strictEqual(pq.nfields(), 1); + }); + + it('has column name', () => { + assert.equal(pq.fname(0), 'my_col'); + }); + + it('has oid type of timestamptz', () => { + assert.strictEqual(pq.ftype(0), 1184); + }); + + it('has value as a date', () => { + const now = new Date(); + const val = pq.getvalue(0); + const date = new Date(Date.parse(val)); + assert.equal(date.getFullYear(), now.getFullYear()); + assert.equal(date.getMonth(), now.getMonth()); + }); + + it('can manually clear result multiple times', () => { + pq.clear(); + pq.clear(); + pq.clear(); + }); +}); + +describe('low-level query integration tests', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + describe('exec', () => { + before(() => { + pq.exec('SELECT * FROM test_data'); + }); + + it('has correct tuples', () => { + assert.strictEqual(pq.ntuples(), 3); + }); + + it('has correct field count', () => { + assert.strictEqual(pq.nfields(), 2); + }); + + it('has correct rows', () => { + assert.strictEqual(pq.getvalue(0, 0), 'brian'); + assert.strictEqual(pq.getvalue(1, 1), '30'); + assert.strictEqual(pq.getvalue(2, 0), ''); + assert.strictEqual(pq.getisnull(2, 0), false); + assert.strictEqual(pq.getvalue(2, 1), ''); + assert.strictEqual(pq.getisnull(2, 1), true); + }); + }); +}); + +describe('sync query with parameters', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + it('works with single string parameter', () => { + const queryText = 'SELECT $1::text as name'; + pq.execParams(queryText, ['Brian']); + assert.strictEqual(pq.ntuples(), 1); + assert.strictEqual(pq.getvalue(0, 0), 'Brian'); + }); + + it('works with a number parameter', () => { + const queryText = 'SELECT $1::int as age'; + pq.execParams(queryText, [32]); + assert.strictEqual(pq.ntuples(), 1); + assert.strictEqual(pq.getvalue(0, 0), '32'); + }); + + it('works with multiple parameters', () => { + const queryText = 'INSERT INTO test_data(name, age) VALUES($1, $2)'; + pq.execParams(queryText, ['Barkley', 4]); + assert.equal(pq.resultErrorMessage(), ''); + }); +}); + +describe('prepare and execPrepared', () => { + let pq: PQ; + + before(() => { + pq = new PQ(); + pq.connectSync(); + createTable(pq); + }); + + after(() => { + pq.finish(); + }); + + const statementName = 'get-name'; + + describe('preparing a statement', () => { + it('works properly', () => { + pq.prepare(statementName, 'SELECT $1::text as name', 1); + assert.ifError(pq.resultErrorMessage()); + assert.equal(pq.resultStatus(), 'PGRES_COMMAND_OK'); + }); + }); + + describe('executing a prepared statement', () => { + it('works properly', () => { + pq.execPrepared(statementName, ['Brian']); + assert.ifError(pq.resultErrorMessage()); + assert.strictEqual(pq.ntuples(), 1); + assert.strictEqual(pq.nfields(), 1); + assert.strictEqual(pq.getvalue(0, 0), 'Brian'); + }); + }); +}); diff --git a/libpq/tsconfig.json b/libpq/tsconfig.json new file mode 100644 index 0000000000..3fe28b1ad1 --- /dev/null +++ b/libpq/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "libpq-tests.ts" + ] +} diff --git a/libpq/tslint.json b/libpq/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/libpq/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 4fe08fc9e66f6b95a96f059e64c8eb0e542b7ebf Mon Sep 17 00:00:00 2001 From: Kei Son Date: Wed, 18 Jan 2017 06:32:37 +0900 Subject: [PATCH 25/72] oauth2orize) Add more interfaces for exchanges (#14038) --- oauth2orize/index.d.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/oauth2orize/index.d.ts b/oauth2orize/index.d.ts index b36272dee6..2c4b0a7601 100644 --- a/oauth2orize/index.d.ts +++ b/oauth2orize/index.d.ts @@ -62,17 +62,35 @@ export namespace exchange { function code(options: Options, issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; function code(issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 5; issue(client, scope, req.body, req.authInfo, issued); + function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 4; issue(client, scope, req.body, issued); + function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 3; issue(client, scope, issued); function clientCredentials(options: Options, issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 2; issue(client, issued); function clientCredentials(options: Options, issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction; function clientCredentials(issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; function clientCredentials(issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 7; issue(client, username, passwd, scope, req.body, req.authInfo, issued); + function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 6; issue(client, username, passwd, scope, req.body, issued); + function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 5; issue(client, username, passwd, scope, issued); function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 4; issue(client, username, passwd, issued); function password(options: Options, issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction; function password(issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; function password(issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 6; issue(client, refreshToken, scope, req.body, req.authInfo, issued); + function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 5; issue(client, refreshToken, scope, req.body, issued); + function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 4; issue(client, refreshToken, scope, issued); function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + // arity == 3; issue(client, refreshToken, issued); function refreshToken(options: Options, issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction; function refreshToken(issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; function refreshToken(issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction; From eef0e1ad4cdcc7fd27783b713a0f78f4f1af582a Mon Sep 17 00:00:00 2001 From: yasupeke Date: Wed, 18 Jan 2017 06:33:37 +0900 Subject: [PATCH 26/72] [webpack-dev-server]Change WebpackDevServer.Configuration.filename type from string to string| RegExp. (#14037) --- webpack-dev-server/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webpack-dev-server/index.d.ts b/webpack-dev-server/index.d.ts index 75651014b1..f794bd62d0 100644 --- a/webpack-dev-server/index.d.ts +++ b/webpack-dev-server/index.d.ts @@ -21,7 +21,7 @@ declare module "webpack-dev-server" { quiet?: boolean; noInfo?: boolean; lazy?: boolean; - filename?: string; + filename?: string| RegExp; watchOptions?: webpack.WatchOptions; publicPath: string; headers?: any; From f73bb9c890ab76fb2a9a2f950b4c7a11a5f8285a Mon Sep 17 00:00:00 2001 From: Bastien Caudan Date: Tue, 17 Jan 2017 22:36:04 +0100 Subject: [PATCH 27/72] jasmine: fix CustomReporter.jasmineDone signature (#14032) - Extract RunDetails interface - Remove test reporter with wrong signature --- jasmine/index.d.ts | 26 ++++++++++++++------------ jasmine/jasmine-tests.ts | 21 +++------------------ 2 files changed, 17 insertions(+), 30 deletions(-) diff --git a/jasmine/index.d.ts b/jasmine/index.d.ts index 5dcf813628..7bf232acba 100644 --- a/jasmine/index.d.ts +++ b/jasmine/index.d.ts @@ -370,13 +370,18 @@ declare namespace jasmine { } interface CustomReporterResult { - description: string, - failedExpectations?: FailedExpectation[], - fullName: string, - id: string; - passedExpectations?: PassedExpectation[], - pendingReason?: string; - status?: string; + description: string, + failedExpectations?: FailedExpectation[], + fullName: string, + id: string; + passedExpectations?: PassedExpectation[], + pendingReason?: string; + status?: string; + } + + interface RunDetails { + failedExpectations: ExpectationResult[]; + order: jasmine.Order } interface CustomReporter { @@ -385,7 +390,7 @@ declare namespace jasmine { specStarted?(result: CustomReporterResult): void; specDone?(result: CustomReporterResult): void; suiteDone?(result: CustomReporterResult): void; - jasmineDone?(): any; + jasmineDone?(runDetails: RunDetails): void; } interface Runner { @@ -549,10 +554,7 @@ declare namespace jasmine { finished: boolean; result: any; messages: any; - runDetails: { - failedExpectations: ExpectationResult[]; - order: jasmine.Order - } + runDetails: RunDetails new (): any; diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 87497e90c2..77aa8cbee3 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -926,7 +926,7 @@ var myReporter: jasmine.CustomReporter = { } console.log(result.passedExpectations.length); }, - + suiteDone: function (result: jasmine.CustomReporterResult) { console.log('Suite: ' + result.description + ' was ' + result.status); for (var i = 0; i < result.failedExpectations.length; i++) { @@ -935,29 +935,14 @@ var myReporter: jasmine.CustomReporter = { } }, - jasmineDone: function() { + jasmineDone: function(runDetails: jasmine.RunDetails) { console.log('Finished suite'); + console.log('Random:', runDetails.order.random); } }; jasmine.getEnv().addReporter(myReporter); -// test for custom reporter which return ES6 Promise in jasmineDone(): -var myShortReporter: jasmine.CustomReporter = { - jasmineDone: function() { - return new Promise(function(resolve, reject) { - setTimeout(() => resolve(), 10000); - }); - } -} - -var jasmineDoneResolved: Promise = myShortReporter.jasmineDone(); -jasmineDoneResolved.then(() => { - console.log("[ShortReporter] : jasmineDone Resolved"); -}); - -jasmine.getEnv().addReporter(myShortReporter); - describe("Randomize Tests", function() { it("should allow randomization of the order of tests", function() { expect(function() { From 8a5f18f78bb1882ddb50c9526cfbc7c5995b2c94 Mon Sep 17 00:00:00 2001 From: bumbleblym Date: Wed, 18 Jan 2017 05:36:49 +0800 Subject: [PATCH 28/72] fix: make options parameter optional (#14031) --- webpack-dev-middleware/index.d.ts | 7 +++++-- webpack-dev-middleware/webpack-dev-middleware-tests.ts | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/webpack-dev-middleware/index.d.ts b/webpack-dev-middleware/index.d.ts index e173d4e3d4..471a0f92ba 100644 --- a/webpack-dev-middleware/index.d.ts +++ b/webpack-dev-middleware/index.d.ts @@ -8,7 +8,10 @@ import { compiler } from 'webpack'; export = WebpackDevMiddleware; -declare function WebpackDevMiddleware(compiler: compiler.Compiler, options: WebpackDevMiddleware.Options): WebpackDevMiddleware.WebpackDevMiddleware & NextHandleFunction; +declare function WebpackDevMiddleware( + compiler: compiler.Compiler, + options?: WebpackDevMiddleware.Options +): WebpackDevMiddleware.WebpackDevMiddleware & NextHandleFunction; declare namespace WebpackDevMiddleware { interface Options { @@ -39,7 +42,7 @@ declare namespace WebpackDevMiddleware { type Reporter = (reporterOptions: ReporterOptions) => void; - type Logger = (message: any) => void; + type Logger = (message?: any, ...optionalParams: any[]) => void; interface WebpackDevMiddleware { close(callback?: () => void): void; diff --git a/webpack-dev-middleware/webpack-dev-middleware-tests.ts b/webpack-dev-middleware/webpack-dev-middleware-tests.ts index b204fbe5d8..63d32332b5 100644 --- a/webpack-dev-middleware/webpack-dev-middleware-tests.ts +++ b/webpack-dev-middleware/webpack-dev-middleware-tests.ts @@ -3,7 +3,10 @@ import * as webpack from 'webpack'; import * as webpackDevMiddleware from 'webpack-dev-middleware'; const compiler = webpack({}); -const webpackDevMiddlewareInstance = webpackDevMiddleware(compiler, { + +let webpackDevMiddlewareInstance = webpackDevMiddleware(compiler); + +webpackDevMiddlewareInstance = webpackDevMiddleware(compiler, { noInfo: false, quiet: false, lazy: true, From b299105c8115935e9850b535c56dd78c2bef4ce5 Mon Sep 17 00:00:00 2001 From: bumbleblym Date: Wed, 18 Jan 2017 05:37:28 +0800 Subject: [PATCH 29/72] feat: Add webpack-hot-middleware (#14030) --- webpack-hot-middleware/index.d.ts | 24 +++++++++++++++++++ webpack-hot-middleware/tsconfig.json | 20 ++++++++++++++++ webpack-hot-middleware/tslint.json | 1 + .../webpack-hot-middleware-tests.ts | 16 +++++++++++++ 4 files changed, 61 insertions(+) create mode 100644 webpack-hot-middleware/index.d.ts create mode 100644 webpack-hot-middleware/tsconfig.json create mode 100644 webpack-hot-middleware/tslint.json create mode 100644 webpack-hot-middleware/webpack-hot-middleware-tests.ts diff --git a/webpack-hot-middleware/index.d.ts b/webpack-hot-middleware/index.d.ts new file mode 100644 index 0000000000..05821a486e --- /dev/null +++ b/webpack-hot-middleware/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for webpack-hot-middleware 2.15 +// Project: https://github.com/glenjamin/webpack-hot-middleware#readme +// Definitions by: Benjamin Lim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { NextHandleFunction } from 'connect'; +import { compiler } from 'webpack'; + +export = WebpackHotMiddleware; + +declare function WebpackHotMiddleware( + compiler: compiler.Compiler, + options?: WebpackHotMiddleware.Options +): NextHandleFunction; + +declare namespace WebpackHotMiddleware { + interface Options { + log?: false | Logger; + path?: string; + heartbeat?: number; + } + + type Logger = (message?: any, ...optionalParams: any[]) => void; +} diff --git a/webpack-hot-middleware/tsconfig.json b/webpack-hot-middleware/tsconfig.json new file mode 100644 index 0000000000..43c1d94e6b --- /dev/null +++ b/webpack-hot-middleware/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "webpack-hot-middleware-tests.ts" + ] +} diff --git a/webpack-hot-middleware/tslint.json b/webpack-hot-middleware/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/webpack-hot-middleware/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/webpack-hot-middleware/webpack-hot-middleware-tests.ts b/webpack-hot-middleware/webpack-hot-middleware-tests.ts new file mode 100644 index 0000000000..e654d012d0 --- /dev/null +++ b/webpack-hot-middleware/webpack-hot-middleware-tests.ts @@ -0,0 +1,16 @@ +import * as express from 'express'; +import * as webpack from 'webpack'; +import * as webpackHotMiddleware from 'webpack-hot-middleware'; + +const compiler = webpack({}); + +let webpackHotMiddlewareInstance = webpackHotMiddleware(compiler); + +webpackHotMiddlewareInstance = webpackHotMiddleware(compiler, { + log: console.log.bind(console), + path: '/__what', + heartbeat: 2000, +}); + +const app = express(); +app.use(webpackHotMiddlewareInstance); From 802ad241463591459d9095c9698bd8bfc3a6c2c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Le=20Dorze?= Date: Tue, 17 Jan 2017 22:56:14 +0100 Subject: [PATCH 30/72] allow enabling logs on IRouteAdditionalConfigurationOptions (#14023) --- hapi/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/hapi/index.d.ts b/hapi/index.d.ts index 5eaf43d7fa..b98e1cdf25 100644 --- a/hapi/index.d.ts +++ b/hapi/index.d.ts @@ -716,7 +716,11 @@ export interface IRouteAdditionalConfigurationOptions { /** ONLY WHEN ADDING NEW ROUTES (not when setting defaults). *route tags used for generating documentation (array of strings). */ - tags?: string[] + tags?: string[]; + + /** Enable logging of routes + */ + log?: boolean; } /** From feefb04e1c975ce868408d62416e5f5c49a2b9bc Mon Sep 17 00:00:00 2001 From: CaiHuan Date: Wed, 18 Jan 2017 05:57:11 +0800 Subject: [PATCH 31/72] remove style isRequire attribute and add react-native-scrollable-tab-view type define file (#14020) * remove style isRequire attribute * commit react-native-scrollable-tab-view * commit react-native-scrollable-tab-view/index.d.ts * changed file extension name * Fix test error * fix no-trailing-whitespace trailing whitespace --- react-native-scrollable-tab-view/index.d.ts | 107 ++++++++++++++++++ ...react-native-scrollable-tab-view-tests.tsx | 48 ++++++++ .../tsconfig.json | 21 ++++ react-native-scrollable-tab-view/tslint.json | 1 + react-native-swiper/index.d.ts | 2 +- 5 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 react-native-scrollable-tab-view/index.d.ts create mode 100644 react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx create mode 100644 react-native-scrollable-tab-view/tsconfig.json create mode 100644 react-native-scrollable-tab-view/tslint.json diff --git a/react-native-scrollable-tab-view/index.d.ts b/react-native-scrollable-tab-view/index.d.ts new file mode 100644 index 0000000000..b2d447c23c --- /dev/null +++ b/react-native-scrollable-tab-view/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for react-native-scrollable-tab-view 0.7 +// Project: https://github.com/brentvatne/react-native-scrollable-tab-view#readme +// Definitions by: CaiHuan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from 'react'; +import { + Animated, + ViewStyle +} from 'react-native'; + +export interface onChangeTabProperties { + // currentPage + i: number; + + // currentPage object + ref: JSX.Element; + + // previousPage + from: number; +} + +export interface renderTabBarProperties { + + goToPage: (pageNumber: number) => void; + + tabs: JSX.Element; + + activeTab: number; + + scrollValue: Animated.Value; + + containerWidth: number; +} + +interface ScrollableTabViewProperties extends React.Props { + + /** + * tabBarPosition (String) Defaults to "top". + * "bottom" to position the tab bar below content. + * "overlayTop" or "overlayBottom" for a semitransparent tab bar that overlays content. Custom + * tab bars must consume a style prop on their outer element to support this feature: style={this.props.style}. + */ + tabBarPosition?: 'top' | 'bottom' | 'overlayTop' | 'overlayBottom'; + + /** + * (Integer) - the index of the initially selected tab, defaults to 0 === first tab + */ + initialPage?: number; + + /** + * (Integer) - set selected tab(can be buggy see + * https://github.com/skv-headless/react-native-scrollable-tab-view/issues/126 + */ + page?: number; + + /** + * onChangeTab (Function) - function to call when tab changes, should accept 1 argument which is + * an Object containing two keys: i: the index of the tab that is selected, ref: the ref of the + * tab that is selected + */ + onChangeTab?: (value: onChangeTabProperties) => void; + + /** + * onScroll (Function) - function to call when the pages are sliding, + * should accept 1 argument which is an Float number representing the page position in the slide frame. + */ + onScroll?: (value: number) => void; + + /** + * renderTabBar (Function:ReactComponent) - accept 1 argument props and should return a component + * to use as the tab bar. The component has goToPage, tabs, activeTab and ref added to the props, + * and should implement setAnimationValue to be able to animate itself along with the tab content. + * You can manually pass the props to the TabBar component. + */ + renderTabBar?: (value: JSX.Element) => JSX.Element; + + /** + * style (View.propTypes.style) + */ + style?: ViewStyle; + + /** + * contentProps (Object) - props that are applied to root ScrollView/ViewPagerAndroid. + * Note that overriding defaults set by the library may break functionality; see the source for details. + */ + contentProps?: React.ScrollViewProperties; + + /** + * scrollWithoutAnimation (Bool) - on tab press change tab without animation. + */ + scrollWithoutAnimation?: boolean; + + /** + * locked (Bool) - disables horizontal dragging to scroll between tabs, default is false. + */ + locked?: boolean; + + /** + * prerenderingSiblingsNumber (Integer) - pre-render nearby # sibling, Infinity === render all + * the siblings, default to 0 === render current page. + */ + prerenderingSiblingsNumber?: number; +} + +export default class ScrollableTabView extends React.Component { +} diff --git a/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx b/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx new file mode 100644 index 0000000000..be501febf9 --- /dev/null +++ b/react-native-scrollable-tab-view/react-native-scrollable-tab-view-tests.tsx @@ -0,0 +1,48 @@ +import * as React from 'react'; +import { + Text +} from 'react-native'; +import ScrollableTabView from 'react-native-scrollable-tab-view'; + +interface MyTextProperties extends React.Props { + tabLabel: string; + + text: string; +} +class MyText extends React.Component { + public constructor(props: MyTextProperties) { + super(props); + } + + public render(): JSX.Element { + return( + this.props.text + ); + } +} + +interface ScrollableTabViewDemoProperties { + +} +class ScrollableTabViewDemo extends React.Component { + + public constructor(props: ScrollableTabViewDemo) { + super(props); + } + + public render(): JSX.Element { + return ( + + + + + + ); + } + + protected componentWillMount?(): void { + } + + protected componentWillUnmount?(): void { + } +} \ No newline at end of file diff --git a/react-native-scrollable-tab-view/tsconfig.json b/react-native-scrollable-tab-view/tsconfig.json new file mode 100644 index 0000000000..a97106da78 --- /dev/null +++ b/react-native-scrollable-tab-view/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-native-scrollable-tab-view-tests.tsx" + ] +} diff --git a/react-native-scrollable-tab-view/tslint.json b/react-native-scrollable-tab-view/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-native-scrollable-tab-view/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-native-swiper/index.d.ts b/react-native-swiper/index.d.ts index 9b6a0f345c..f1ff914346 100644 --- a/react-native-swiper/index.d.ts +++ b/react-native-swiper/index.d.ts @@ -12,7 +12,7 @@ interface SwiperProperties extends React.Props { horizontal?: boolean; - style: ViewStyle; + style?: ViewStyle; pagingEnabled?: boolean; From af1399fc19a063a0e1477701aa89e38654aa4a64 Mon Sep 17 00:00:00 2001 From: John Chijioke Date: Tue, 17 Jan 2017 22:57:33 +0100 Subject: [PATCH 32/72] Update index.d.ts (#14019) Add responseType option to Auth0ClientOptions and error string to Auth0DecodedHash --- auth0-js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 2907eba686..bd97fed1cc 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -35,6 +35,7 @@ interface Auth0ClientOptions { clientID: string; callbackURL: string; callbackOnLocationHash?: boolean; + responseType?: string; domain: string; forceJSONP?: boolean; } @@ -87,6 +88,7 @@ interface Auth0DecodedHash { idToken: string; profile: Auth0UserProfile; state: any; + error: string; } interface Auth0PopupOptions { From 57d1aeb1c96278b8629b740413c396ab375909c7 Mon Sep 17 00:00:00 2001 From: Meno Abels Date: Tue, 17 Jan 2017 22:58:26 +0100 Subject: [PATCH 33/72] sshpk: initial type definition (#14018) * sshpk: initial type definition * * fixing the tslint problems * * a little lint + the right version header --- sshpk/index.d.ts | 378 +++++++++++++++++++++++++++++++++++++++++++ sshpk/sshpk-tests.ts | 6 + sshpk/tsconfig.json | 20 +++ sshpk/tslint.json | 1 + 4 files changed, 405 insertions(+) create mode 100644 sshpk/index.d.ts create mode 100644 sshpk/sshpk-tests.ts create mode 100644 sshpk/tsconfig.json create mode 100644 sshpk/tslint.json diff --git a/sshpk/index.d.ts b/sshpk/index.d.ts new file mode 100644 index 0000000000..dd42683527 --- /dev/null +++ b/sshpk/index.d.ts @@ -0,0 +1,378 @@ +// Type definitions for sshpk 1.10 +// Project: github.com/arekinath/node-sshpk +// Definitions by: Meno Abels +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare class SshPK { +} + +declare namespace SshPK { + + export class Algo { + parts: string[]; + sizePart?: string; + normalize?: boolean; + } + + + export class algInfo { + dsa: Algo; + rsa: Algo; + ecdsa: Algo; + ed25519: Algo; + curve25519: Algo; + } + + export class algPrivInfo { + dsa: Algo; + rsa: Algo; + ecdsa: Algo; + ed25519: Algo; + curve25519: Algo; + } + + export class hashAlgs { + md5: boolean; + sha1: boolean; + sha256: boolean; + sha384: boolean; + sha512: boolean; + } + + export class Curve { + size: number; + pkcs8oid: string; + p: Buffer; + a: Buffer; + b: Buffer; + s: Buffer; + n: Buffer; + G: Buffer; + } + + export class curves { + nistp256: Curve; + nistp384: Curve; + nistp512: Curve; + } + + export class algs { + info: algInfo; + privInfo: algPrivInfo; + hashAlgs: hashAlgs; + curves: curves; + } + + + export class Certificate { + subjects: Identity[]; + issuer: string; + subjectKey: string; + issuerKey: string; + signatures: string; + serial: string; + validFrom: string; + validUntil: string; + static formats: Formats; + constructor(opts: any); + + toBuffer(format: string, options: any): Buffer; + + toString(format: string, options: any): string; + + fingerprint(algo: string): Fingerprint; + + hash(algo: string): string; + + isExpired(when: Date): boolean; + + isSignedBy(issuerCert: Certificate): boolean; + + isSignedByKey(issuerKey: Key): boolean; + + signWith(key: Key): void; + + static createSelfSigned(subjectOrSubjects: string, key: Key, options: any): Certificate; + + static create(subjectOrSubjects: string, key: Key, issuer: string, issuerKey: PrivateKey, options: any): Certificate; + + static parse(data: string|Buffer, format: string, options: any): Certificate; + + static isCertificate(data: string|Buffer, ver: string): boolean; + + } + + + export class DiffieHellman { + + constructor(key: Key); + + getPublicKey(): Key; + getPrivateKey(): PrivateKey; + getKey(): PrivateKey; + setKey(key: PrivateKey): void; + setPrivateKey(key: PrivateKey): void; + + computeSecret(otherpk: PrivateKey): Buffer; + + generateKey(): PrivateKey; + generateKeys(): PrivateKey; + } + + export class X9ECParameters { + G: any; + g: any; + n: any; + h: any; + } + + export class ECPublic { + constructor(params: X9ECParameters, buffer: Buffer); + } + + export class ECPrivate { + constructor(params: X9ECParameters, buffer: Buffer); + deriveSharedSecret(pk: Key): Buffer; + } + + + export class Verifier { + constructor(key: Key, hashAlgo: string); + + update(chunk: string|Buffer): void; + + verify(signature: string): boolean; + } + + export class Signer { + + constructor(key: Key, hashAlgo: string); + + update(chunk: string|Buffer): void; + sign(): Signature; + } + + + export class FingerprintFormatError implements Error { + name: string; + message: string; + constructor(fp: Fingerprint, format: string); + } + + export class InvalidAlgorithmError implements Error { + name: string; + message: string; + constructor(algo: string); + } + + export class KeyParseError implements Error { + name: string; + message: string; + constructor(name: string, format: string, innerErr: any); + } + + export class SignatureParseError implements Error { + name: string; + message: string; + constructor(type: string, format: string, innerErr: any); + } + + export class CertificateParseError implements Error { + name: string; + message: string; + constructor(name: string, format: string, innerErr: any); + } + + export class KeyEncryptedError implements Error { + name: string; + message: string; + constructor(name: string, format: string); + } + + + export class Fingerprint { + algorithm: string; + hash: string; + type: string; + constructor(opts: any); + + toString(format?: string): string; + matches(other: Fingerprint): boolean; + addColons(fp: string): string; + base64Strip(fp: string): string; + sshBase64Format(alg: string, h: string): string; + isFingerprint(obj: string|Buffer, ver: string): boolean; + + static parse(fp: string, options: any): Fingerprint; + + } + + export class Identity { + cn: string; + components: string[]; + componentLookup: any; + type: string; + hostname: string; + uid: string; + email: string; + constructor(opts: any); + + toString(): string; + + toAsn1(der: Buffer|string, tag: string): void; + + equals(other: Identity): boolean; + + static forHost(hostname: string): Identity; + static forUser(uid: string): Identity; + static forEmail(email: string): Identity; + static parseDN(dn: string): Identity; + static parseAsn1(dn: Buffer|string, top: string): Identity; + static isIdentity(dn: Buffer|string, ver: string): boolean; + } + + + export class Format { + read: (buf: Buffer, options?: any) => Buffer; + write: (key: Key, options?: any) => Buffer; + } + + export class Formats { + auto: Format; + pem: Format; + pkcs1: Format; + pkcs8: Format; + rfc4253: Format; + ssh: Format; + "ssh-private": Format; + openssh: Format; + } + + export class Verify { + verify(data: string, fmt: string): boolean; + } + + export class Key { + type: string; + parts: string; + part: string; + comment?: string; + source?: string; + curve?: string; + size: number; + constructor(opts: any); + + static formats: Formats; + + toBuffer(format: string, options: any): Buffer; + toString(format: string, options: any): string; + hash(algo: string): Buffer; + fingerprint(algo: string): Fingerprint; + defaultHashAlgorithm(): string; + createVerify(algo: string): Verify; + createDiffieHellman(): DiffieHellman; + createDH(): DiffieHellman; + + static parse(data: string|Buffer, format: string, options: any): Key; + + static isKey(obj: string|Buffer, ver: string): boolean; + + } + + export class PrivateKey { + constructor(opts: any); + static formats: Formats; + toBuffer(format: string, options: any): Buffer; + hash(algo: string): Buffer; + toPublic(): Key; + derive(newType: string, newSize: number): PrivateKey; + createVerify(hashAlgo: string): Key; + createSign(hashAlgo: string): Signer; + + static parse(data: string|Buffer, format: string, options: any): PrivateKey; + static isPrivateKey(data: string|Buffer, ver: string): boolean; + + } + + + export class Signature { + constructor(opts: any); + toBuffer(format: string): Buffer; + toString(format: string): string; + + static parse(data: string|Buffer, type: string, format: string): Signature; + + static isSignature(obj: string|Buffer, ver: string): boolean; + + } + + export class SSHPart { + data: Buffer; + } + + export class SSHBuffer { + constructor(opts: any); + toBuffer(): Buffer; + atEnd(): boolean; + remainder(): Buffer; + skip(n: number): void; + expand(): void; + readPart(): SSHPart; + readBuffer(): Buffer; + readString(): string; + readInt(): number; + readInt64(): Buffer; + readChar(): string; + writeBuffer(buf: Buffer): void; + writeString(buf: string): void; + writeCString(buf: string): void; + writeInt(buf: number): void; + writeInt64(buf: Buffer): void; + writeChar(buf: string): void; + writePart(buf: SSHPart): void; + write(buf: Buffer): void; + + } + + + export function bufferSplit(buf: Buffer, chr: string): Buffer[]; + export function addRSAMissing(key: PrivateKey): void; + export function calculateDSAPublic(g: Buffer, p: Buffer, x: Buffer): Buffer; + export function mpNormalize(buf: Buffer): Buffer; + export function ecNormalize(buf: Buffer, addZero: boolean): Buffer; + export function countZeros(buf: Buffer): number; + export function assertCompatible(obj: any, klass: any, needVer: string, name: string): void; + export function isCompatible(obj: any, klass: any, needVer: string): boolean; + export class OpenSllKeyDeriv { + key: Buffer; + iv: Buffer; + } + export function opensslKeyDeriv(cipher: string, salt: string, passphrase: string, count: number): OpenSllKeyDeriv; + + export class OpensshCipherInfo { + keySize: number; + blockSize: number; + opensslName: string; + } + export function opensshCipherInfo(cipber: string): OpensshCipherInfo; + + export function parseKey(data: string|Buffer, format: string, options?: any): Key; + export function parseFingerprint(fp: string, options?: any): Fingerprint; + export function parseSignature(data: string|Buffer, type: string, format: string): Signature; + export function parsePrivateKey(data: string|Buffer, format: string, options?: any): PrivateKey; + + export function parseCertificate(data: string|Buffer, format: string, options?: any): Certificate; + export function createSelfSignedCertificate(subjectOrSubjects: string, key: Key, options?: any): Certificate; + export function createCertificate(subjectOrSubjects: string, key: Key, issuer: string, + issuerKey: PrivateKey, options?: any): Certificate; + + export function identityFromDN(dn: string): Identity; + export function identityForHost(hostname: string): Identity; + export function identityForUser(uid: string): Identity; + export function identityForEmail(email: string): Identity; + +} + +export = SshPK; diff --git a/sshpk/sshpk-tests.ts b/sshpk/sshpk-tests.ts new file mode 100644 index 0000000000..832045549a --- /dev/null +++ b/sshpk/sshpk-tests.ts @@ -0,0 +1,6 @@ + +import * as sshpk from 'sshpk'; + +const cert = sshpk.parseCertificate("", "pem"); +const fpr = cert.fingerprint("sha256").toString("hex"); +const cn = cert.subjects[0].cn; diff --git a/sshpk/tsconfig.json b/sshpk/tsconfig.json new file mode 100644 index 0000000000..d2288e634f --- /dev/null +++ b/sshpk/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sshpk-tests.ts" + ] +} diff --git a/sshpk/tslint.json b/sshpk/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/sshpk/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From e584d29c6c2e96388f89adc3c232867304a53feb Mon Sep 17 00:00:00 2001 From: Titan Date: Wed, 18 Jan 2017 06:05:16 +0800 Subject: [PATCH 34/72] Add types for hiredis (#14015) --- hiredis/hiredis-tests.ts | 13 +++++++++++++ hiredis/index.d.ts | 20 ++++++++++++++++++++ hiredis/tsconfig.json | 20 ++++++++++++++++++++ hiredis/tslint.json | 1 + 4 files changed, 54 insertions(+) create mode 100644 hiredis/hiredis-tests.ts create mode 100644 hiredis/index.d.ts create mode 100644 hiredis/tsconfig.json create mode 100644 hiredis/tslint.json diff --git a/hiredis/hiredis-tests.ts b/hiredis/hiredis-tests.ts new file mode 100644 index 0000000000..9a32fb9755 --- /dev/null +++ b/hiredis/hiredis-tests.ts @@ -0,0 +1,13 @@ +import { Reader, Config, createConnection } from "hiredis"; + +const socket = createConnection(6379, "localhost"); + +socket.write("INFO"); + +const reader = new Reader({ return_buffers: false }); + +// Data comes in +reader.feed("$5\r\nhello\r\n"); + +// Reply comes out +reader.get(); // => "hello" diff --git a/hiredis/index.d.ts b/hiredis/index.d.ts new file mode 100644 index 0000000000..727e4f4a03 --- /dev/null +++ b/hiredis/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for hiredis 0.5 +// Project: http://github.com/redis/hiredis-node +// Definitions by: Titan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as net from "net"; + +export interface Config { + return_buffers: boolean; +} + +export class Reader { + constructor(config?: Config); + feed(reply: string | Buffer): void; + get(): string | Buffer; +} + +export function createConnection(port: number, host: string): net.Socket; diff --git a/hiredis/tsconfig.json b/hiredis/tsconfig.json new file mode 100644 index 0000000000..d6665e66b6 --- /dev/null +++ b/hiredis/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hiredis-tests.ts" + ] +} diff --git a/hiredis/tslint.json b/hiredis/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/hiredis/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 4f35aef09435dc94999b4fcee4bb6a01d89ba48d Mon Sep 17 00:00:00 2001 From: Ahmad Ferdous Bin Alam Date: Tue, 17 Jan 2017 18:37:56 -0500 Subject: [PATCH 35/72] Remove invalid parameter id from DeleteDocumentByQueryParams (#14014) The parameter list of deleteByQuery function does not have `id`. The relevant documentation is available at https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-deletebyquery Even the Elasticsearch documentation available at https://www.elastic.co/guide/en/elasticsearch/reference/5.x/docs-delete-by-query.html does not refer to any id parameter for that function. --- elasticsearch/elasticsearch-tests.ts | 11 +++++++++++ elasticsearch/index.d.ts | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 98d5a6c925..1be3f740bc 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -32,6 +32,17 @@ client.indices.delete({ }, function (error) { }); +client.deleteByQuery({ + index: 'test_index', + type: 'test_type', + body: { + query: { + } + } +}).then(function (response) { +}, function (error) { +}); + client.create({ index: 'index', type: 'type' diff --git a/elasticsearch/index.d.ts b/elasticsearch/index.d.ts index faeab9eb38..84c8f281f9 100644 --- a/elasticsearch/index.d.ts +++ b/elasticsearch/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for elasticsearch 5.0 // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski , Margus Lamp +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski , Margus Lamp , Ahmad Ferdous Bin Alam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { From d550329fc6e1caf5302c45e7fef19c5e087f04af Mon Sep 17 00:00:00 2001 From: fabio-silva Date: Tue, 17 Jan 2017 23:50:17 +0000 Subject: [PATCH 36/72] added 'showCustomRangeLabel' option (#14074) --- daterangepicker/daterangepicker-tests.ts | 10 ++++++++++ daterangepicker/index.d.ts | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts index 38264bb0b3..04ff80c0e8 100644 --- a/daterangepicker/daterangepicker-tests.ts +++ b/daterangepicker/daterangepicker-tests.ts @@ -55,5 +55,15 @@ function tests_simple() { } }, cb); + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()] + }, + showCustomRangeLabel: false + }, cb); + }); } diff --git a/daterangepicker/index.d.ts b/daterangepicker/index.d.ts index 68ae67c485..7929474994 100644 --- a/daterangepicker/index.d.ts +++ b/daterangepicker/index.d.ts @@ -125,6 +125,10 @@ declare namespace daterangepicker { * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. */ alwaysShowCalendars?: boolean; + /** + * Whether to show the 'Custom Range' label or just pre-defined ranges + */ + showCustomRangeLabel?: boolean; } interface Locale { From f54bb800a03fc728901360531fb0f2b24ab31b38 Mon Sep 17 00:00:00 2001 From: Ian MacLeod Date: Tue, 17 Jan 2017 16:02:39 -0800 Subject: [PATCH 37/72] [webfontloader] Fix typescript interface (#13955) The typescript configuration field expects a [single string id](https://github.com/typekit/webfontloader/blob/33bec9da7ca4b0a46b1efbaca705c2ae5029840b/src/modules/typekit.js#L30), not an array --- webfontloader/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webfontloader/index.d.ts b/webfontloader/index.d.ts index 44e43a0811..bffe96c560 100644 --- a/webfontloader/index.d.ts +++ b/webfontloader/index.d.ts @@ -42,7 +42,7 @@ declare namespace WebFont { text?: string; } export interface Typekit { - id?:Array; + id?:string; } export interface Custom { families?:Array; From 8e08375093108eb791e7b1a47cec072e10fa92a4 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Tue, 17 Jan 2017 16:03:46 -0800 Subject: [PATCH 38/72] Explain how to use custom matchers (#13957) The test only compile because `jasmine-tests.ts` doesn't import or export anything, and so the typescript compiler thinks it is a global definition file. I've added a note explaining how normal users would declare their custom matchers. --- jasmine/jasmine-tests.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 77aa8cbee3..4632eb8b4c 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -872,6 +872,14 @@ var customMatchers: jasmine.CustomMatcherFactories = { } }; // add the custom matchers to interface jasmine.Matchers via TypeScript declaration merging +// if your test files import or export anything, you'll want to use: +// declare global { +// namespace jasmine { +// interface Matchers { +// ... +// } +// } +// } declare namespace jasmine { interface Matchers { toBeGoofy(expected?: any): boolean; From 1852aeb3cb1db70d7cee771f2e6418c12d74eb4f Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 17 Jan 2017 16:04:16 -0800 Subject: [PATCH 39/72] Remove old scripts (#13967) --- scripts/delete-tscparams.ts | 40 ------------------ scripts/fix-reference-comments.ts | 50 ---------------------- scripts/rename-entry-points.ts | 70 ------------------------------- scripts/rename-proper-modules.ts | 18 -------- 4 files changed, 178 deletions(-) delete mode 100644 scripts/delete-tscparams.ts delete mode 100644 scripts/fix-reference-comments.ts delete mode 100644 scripts/rename-entry-points.ts delete mode 100644 scripts/rename-proper-modules.ts diff --git a/scripts/delete-tscparams.ts b/scripts/delete-tscparams.ts deleted file mode 100644 index 49bfef899c..0000000000 --- a/scripts/delete-tscparams.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -import * as fs from 'fs'; -import * as path from 'path'; - -const home = path.join(__dirname, '..'); - -function forEachTypingDir(callback: (fullPath: string, dirName: string) => void) { - fs.readdir(home, (err, dirs) => { - if (err) throw err; - for (const dir of dirs) { - const fullPath = path.join(home, dir); - fs.lstat(fullPath, (err, stats) => { - if (err) throw err; - if (stats.isDirectory()) { - callback(fullPath, dir); - } - }); - } - }); -} - -forEachTypingDir(typingPath => { - fs.readdir(typingPath, (err, files) => { - if(err) throw err; - for(const file of files) { - if (/tscparams$/.test(file)) { - const fullPath = path.join(typingPath, file); - - fs.readFile(fullPath, 'utf-8', (err, paramText) => { - if(err) throw err; - - if (paramText.length <= 2) { - fs.unlink(fullPath); - } - }); - } - } - }); -}); diff --git a/scripts/fix-reference-comments.ts b/scripts/fix-reference-comments.ts deleted file mode 100644 index ca2a18238b..0000000000 --- a/scripts/fix-reference-comments.ts +++ /dev/null @@ -1,50 +0,0 @@ -/// - -import * as fs from 'fs'; -import * as path from 'path'; - -const home = path.join(__dirname, '..'); - -function forEachTypingDir(callback: (fullPath: string, dirName: string) => void) { - fs.readdir(home, (err, dirs) => { - if (err) throw err; - for (const dir of dirs) { - const fullPath = path.join(home, dir); - fs.lstat(fullPath, (err, stats) => { - if (err) throw err; - if (stats.isDirectory()) { - callback(fullPath, dir); - } - }); - } - }); -} - -const referenceRegex = /^\/\/\/\s?\(\s*)$/gm; - -forEachTypingDir(typingPath => { - fs.readdir(typingPath, (err, files) => { - if (err) throw err; - for (const file of files) { - if (/\.ts(x?)$/.test(file)) { - const fullPath = path.join(typingPath, file); - - console.log('Read ' + fullPath); - let fileContent = fs.readFileSync(fullPath, 'utf-8'); - let match = referenceRegex.exec(fileContent); - while(match !== null) { - const referand = match[1]; - const referandFullPath = path.join(path.dirname(fullPath), referand); - if (!fs.existsSync(referandFullPath)) { - console.log(`${fullPath} references missing file ${referandFullPath}`); - fileContent = fileContent.replace(match[0], ''); - fs.writeFileSync(fullPath, fileContent, 'utf-8'); - } - - match = referenceRegex.exec(fileContent); - - } - } - } - }); -}); diff --git a/scripts/rename-entry-points.ts b/scripts/rename-entry-points.ts deleted file mode 100644 index 14fce05ce3..0000000000 --- a/scripts/rename-entry-points.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// - -import * as fs from 'fs'; -import * as path from 'path'; - -function repeat(s: string, count: number) { - return Array(count + 1).join(s); -} - -function checkDir(home: string, count: number) { - fs.readdir(home, (err, dirs) => { - if (err) throw err; - - for (const dir of dirs.map(d => path.join(home, d))) { - fs.lstat(dir, (err, stats) => { - if(dir.indexOf('.git') > 0) return; - - if (err) throw err; - if (stats.isDirectory()) { - checkDir(dir, count + 1); - fs.readdir(dir, (err, files) => { - if (err) throw err; - const target = path.join(dir, 'tsconfig.json'); - fs.exists(target, exists => { - if (exists) { - const old = JSON.parse(fs.readFileSync(target, 'utf-8')); - - let entryPoint: string; - let definitionFiles = files.filter(f => (f.indexOf('.d.ts') > 0)); - if (definitionFiles.length === 1) { - entryPoint = definitionFiles[0]; - } else if(fs.existsSync(path.join(dir, 'index.d.ts'))) { - entryPoint = 'index.d.ts'; - } else { - entryPoint = path.basename(dir) + '.d.ts'; - } - - if (!fs.existsSync(path.join(dir, entryPoint))) { - console.log('No file ' + entryPoint + ' exists in ' + dir + ' so deleting it'); - fs.unlink(target); - return; - } - - let testFile: string | undefined = path.join(dir, path.basename(dir) + '-tests.ts'); - if (!fs.existsSync(testFile)) { - let onlyTest = files.filter(f => f.toLowerCase().indexOf('-tests.ts') > 0)[0]; - if (onlyTest) { - testFile = path.join(dir, onlyTest); - } else { - testFile = undefined; - } - } - if (testFile) { - old['files'] = ['index.d.ts', path.basename(testFile)]; - } else { - old['files'] = ['index.d.ts']; - } - - fs.writeFileSync(target, JSON.stringify(old, undefined, 4)); - console.log('Write to ' + target); - } - }); - }); - } - }); - } - }); -} - -checkDir(path.join(__dirname, '..'), 1); diff --git a/scripts/rename-proper-modules.ts b/scripts/rename-proper-modules.ts deleted file mode 100644 index ae5179e401..0000000000 --- a/scripts/rename-proper-modules.ts +++ /dev/null @@ -1,18 +0,0 @@ -/// - -import * as fs from 'fs'; -import * as path from 'path'; - -const data = JSON.parse(fs.readFileSync(path.join(__dirname, '../../publish-typings/data/definitions.json'), 'utf-8')); - -Object.keys(data).forEach(libName => { - const libData = data[libName]; - if(libData.kind === 'ProperModule') { - if (libData.definitionFilename !== 'index.d.ts') { - console.log(`${libName} needs renaming from ${libData.definitionFilename}`); - const src = path.join(__dirname, '..', libName, libData.definitionFilename); - const dst = path.join(__dirname, '..', libName, 'index.d.ts'); - fs.rename(src, dst); - } - } -}); From 403527dc84f870ac0f01f1721fd6e652ac0ed4bc Mon Sep 17 00:00:00 2001 From: mad-mike Date: Wed, 18 Jan 2017 01:17:26 +0100 Subject: [PATCH 40/72] Update descriptions for simple-oauth2 (#14072) --- simple-oauth2/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/simple-oauth2/index.d.ts b/simple-oauth2/index.d.ts index 72d960f946..ec4c1eba83 100644 --- a/simple-oauth2/index.d.ts +++ b/simple-oauth2/index.d.ts @@ -24,7 +24,7 @@ interface ModuleOptions { tokenHost: string, /** String path to request an access token. Default to /oauth/token. */ tokenPath?: string, - /** String path to revoken an access token. Default to /oauth/revoke. */ + /** String path to revoke an access token. Default to /oauth/revoke. */ revokePath?: string, /** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */ authorizeHost?: string, @@ -34,8 +34,9 @@ interface ModuleOptions { /** optional object used to set global options to the internal http library (request-js). */ http?: {}; options?: { - /** Wheather or not the client.id/client.secret params are sent in the request body. Defaults to true. */ + /** Whether or not the client.id/client.secret params are sent in the request body. Defaults to true. */ useBodyAuth?: boolean, + /** Whether or not the Basic Authorization header should be sent at the token request. */ useBasicAuthorizationHeader?: boolean }; } From e22cae7de6e0a2328d23fcbbf685afde5423f813 Mon Sep 17 00:00:00 2001 From: Garth Kidd Date: Wed, 18 Jan 2017 11:21:42 +1100 Subject: [PATCH 41/72] Ensure boom.BoomError can be cast to Error (#14075) --- boom/boom-tests.ts | 1 + boom/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/boom/boom-tests.ts b/boom/boom-tests.ts index 4c2f23ed64..8b5c3bdce6 100644 --- a/boom/boom-tests.ts +++ b/boom/boom-tests.ts @@ -5,3 +5,4 @@ import Boom = require('boom'); Boom.create(500, 'Internal server error', { timestamp: Date.now() }); Boom.wrap(new Error('test'), 400); Boom.badRequest('Invalid cookies'); +Boom.unauthorized() as Error; diff --git a/boom/index.d.ts b/boom/index.d.ts index b252fad1e1..e8cfb5722f 100644 --- a/boom/index.d.ts +++ b/boom/index.d.ts @@ -16,6 +16,7 @@ declare namespace Boom { isServer: boolean; message: string; output: Output; + name: string; } export interface Output { From 9001e6d0ef5dccf1a8eee490427456536ab5afaf Mon Sep 17 00:00:00 2001 From: Sema Date: Wed, 18 Jan 2017 01:24:32 +0100 Subject: [PATCH 42/72] artyom.js - Created typescript definition file (#13947) * Initial version of types for artyom.js * Added headers and documentation * Removed tslint exception In local, the npm run lint said that this header is not allowed, but in travis seems to work * Added "noImplicitThis": true, * Added MAJOR.MINOR to .d.ts header --- artyom.js/artyom.js-tests.ts | 32 +++ artyom.js/index.d.ts | 513 +++++++++++++++++++++++++++++++++++ artyom.js/tsconfig.json | 20 ++ artyom.js/tslint.json | 1 + 4 files changed, 566 insertions(+) create mode 100644 artyom.js/artyom.js-tests.ts create mode 100644 artyom.js/index.d.ts create mode 100644 artyom.js/tsconfig.json create mode 100644 artyom.js/tslint.json diff --git a/artyom.js/artyom.js-tests.ts b/artyom.js/artyom.js-tests.ts new file mode 100644 index 0000000000..e70704ad4e --- /dev/null +++ b/artyom.js/artyom.js-tests.ts @@ -0,0 +1,32 @@ +import artyomjs = require('artyom.js'); + +// Get an unique ArtyomJS instance +let artyom = artyomjs.ArtyomBuilder.getInstance(); + +// Add a command (not smart) +artyom.addCommands({ + description: 'Test command', + indexes: ['hello', 'hi'], + action: (i: number) => { + console.log('hello action'); + } +}); + +// Add a smart command +artyom.addCommands({ + description: 'Test command 2', + smart: true, + indexes: ['test *'], + action: (i: number, wildcard: string) => { + console.log('wildcard: ', wildcard); + } +}); + +// Get the browser voices +artyom.getVoices(); + +// Get all supported languages for Artyom +artyom.getLanguage(); + +// Get the artyom.js version +artyom.getVersion(); \ No newline at end of file diff --git a/artyom.js/index.d.ts b/artyom.js/index.d.ts new file mode 100644 index 0000000000..d96880395f --- /dev/null +++ b/artyom.js/index.d.ts @@ -0,0 +1,513 @@ +// Type definitions for artyom.js 1.0 +// Project: https://github.com/sdkcarlos/artyom.js +// Definitions by: Sema García (José Manuel García) +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Extension of Window interface + */ +interface ArtyomWindow extends Window { + webkitSpeechRecognition: any; + SpeechRecognition: any; + SpeechSynthesisUtterance: any; +} + +interface SpeechRecognition extends EventTarget { + grammars: SpeechGrammarList; + lang: string; + continuous: boolean; + interimResults: boolean; + maxAlternatives: number; + serviceURI: string; + start(): void; + stop(): void; + abort(): void; + onaudiostart: (ev: Event) => any; + onsoundstart: (ev: Event) => any; + onspeechstart: (ev: Event) => any; + onspeechend: (ev: Event) => any; + onsoundend: (ev: Event) => any; + onresult: (ev: SpeechRecognitionEvent) => any; + onnomatch: (ev: SpeechRecognitionEvent) => any; + onerror: (ev: SpeechRecognitionError) => any; + onstart: (ev: Event) => any; + onend: (ev: Event) => any; +} + +interface SpeechRecognitionStatic { + prototype: SpeechRecognition; + new (): SpeechRecognition; +} + +declare var SpeechRecognition: SpeechRecognitionStatic; +declare var webkitSpeechRecognition: SpeechRecognitionStatic; + +interface SpeechRecognitionError extends Event { + error: string; + message: string; +} + +interface SpeechRecognitionAlternative { + transcript: string; + confidence: number; +} + +interface SpeechRecognitionResult { + length: number; + item(index: number): SpeechRecognitionAlternative; + [index: number]: SpeechRecognitionAlternative; + isFinal: boolean; +} + +interface SpeechRecognitionResultList { + length: number; + item(index: number): SpeechRecognitionResult; + [index: number]: SpeechRecognitionResult; +} + +interface SpeechRecognitionEvent extends Event { + resultIndex: number; + results: SpeechRecognitionResultList; + interpretation: any; + emma: Document; +} + +interface SpeechGrammar { + src: string; + weight: number; +} + +interface SpeechGrammarStatic { + prototype: SpeechGrammar; + new (): SpeechGrammar; +} + +declare var SpeechGrammar: SpeechGrammarStatic; +declare var webkitSpeechGrammar: SpeechGrammarStatic; + +interface SpeechGrammarList { + length: number; + item(index: number): SpeechGrammar; + [index: number]: SpeechGrammar; + addFromURI(src: string, weight: number): void; + addFromString(string: string, weight: number): void; +} + +interface SpeechGrammarListStatic { + prototype: SpeechGrammarList; + new (): SpeechGrammarList; +} + +declare var SpeechGrammarList: SpeechGrammarListStatic; +declare var webkitSpeechGrammarList: SpeechGrammarListStatic; + +interface SpeechSynthesis extends EventTarget { + pending: boolean; + speaking: boolean; + paused: boolean; + + onvoiceschanged: (ev: Event) => any; + speak(utterance: SpeechSynthesisUtterance): void; + cancel(): void; + pause(): void; + resume(): void; + getVoices(): SpeechSynthesisVoice[]; +} + +interface SpeechSynthesisGetter { + speechSynthesis: SpeechSynthesis; +} + +declare var speechSynthesis: SpeechSynthesis; + +interface SpeechSynthesisUtterance extends EventTarget { + text: string; + lang: string; + voice: SpeechSynthesisVoice; + volume: number; + rate: number; + pitch: number; + + onstart: (ev: SpeechSynthesisEvent) => any; + onend: (ev: SpeechSynthesisEvent) => any; + onerror: (ev: SpeechSynthesisErrorEvent) => any; + onpause: (ev: SpeechSynthesisEvent) => any; + onresume: (ev: SpeechSynthesisEvent) => any; + onmark: (ev: SpeechSynthesisEvent) => any; + onboundary: (ev: SpeechSynthesisEvent) => any; +} + +interface SpeechSynthesisUtteranceStatic { + prototype: SpeechSynthesisUtterance; + new (text?: string): SpeechSynthesisUtterance; +} + +declare var SpeechSynthesisUtterance: SpeechSynthesisUtteranceStatic; + +interface SpeechSynthesisEvent extends Event { + utterance: SpeechSynthesisUtterance; + charIndex: number; + elapsedTime: number; + name: string; +} + +interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent { + error: string; +} + +interface SpeechSynthesisVoice { + voiceURI: string; + name: string; + lang: string; + localService: boolean; + default: boolean; +} + +declare namespace Artyom { + + interface ArtyomDevice { + isChrome(): boolean; + isMobile(): boolean; + } + + interface ArtyomBrowserVoiceObject { + default: boolean; + lang: string; + localService: false; + name: string; + voiceURI: string; + } + + interface ArtyomConfigProperties { + /** Set the default language of artyom with this property */ + lang?: string; + recognizing?: boolean; + /** Choose if should listen one command and then stops, or listening forever */ + continuous?: boolean; + /** Moderates the speed with which Artyom talks (0 ~ 1) */ + speed?: number; + /** Adjust the volume of the voice of artyom */ + volume?: number; + /** If listen is equal to true the voice recognition will be started otherwise this property can be ignored */ + listen: boolean; + /** Recognition mode: normal, quick, remote */ + mode?: string; + /** Displays all the grammars recognized in the console */ + debug: boolean; + helpers?: { + redirectRecognizedTextOutput: any; + remoteProcessorHandler: any; + lastSay: any; + }; + /** Set a keyword that allows your command to be executed immediately when you say this word (Useful in noisy environments) */ + executionKeyword?: string; + /** Set a keyword that allows to enable the command recognition automatically if this word is recognized while artyom is paused (artyom.dontObey) */ + obeyKeyword?: string; + speaking?: boolean; + obeying?: boolean; + soundex?: boolean; + } + + interface ArtyomCommand { + /** Triggers of the command */ + indexes: string[]; + /** Logic to execute when the command is triggered */ + action: (i: number, wildcard?: string, full?: string) => void; + /** Description of the command */ + description?: string; + /** Flag to specify is a command is either normal or smart */ + smart?: boolean; + } + + interface ArtyomFlags { + restartRecognition: boolean; + } + + interface ArtyomRecognizer { + lang: string; + continuous: boolean; + interimResults: boolean; + start(): void; + stop(): void; + onstart(): void; + onresult(event: any): void; + onerror(event: any): void; + onend(): void; + } + + export interface ArtyomJS { + /** + * Contains some basic information that artyom needs to know as the type of device and browser + * @see http://ourcodeworld.com/projects/projects-documentation/6/read-doc/artyom-device/artyom-js + */ + device: ArtyomDevice; + + /** + * Object which provides the speech interface, and set some of its attributes and event handlers + */ + artyomWSR: ArtyomRecognizer; + + /** + * Artyom can return inmediately the voices available in your browser. + * @see http://ourcodeworld.com/projects/projects-documentation/14/read-doc/artyom-getvoices/artyom-js + * @returns {Array} + */ + getVoices(): SpeechSynthesisVoice[]; + + /** + * Returns an array with all the available commands for artyom. + * @see http://ourcodeworld.com/projects/projects-documentation/10/read-doc/artyom-getavailablecommands/artyom-js + * @returns {Array} + */ + getAvailableCommands(): ArtyomCommand[]; + + /** + * Set up artyom for the application. This function will set the default language used by artyom + * or notice the user if artyom is not supported in the actual browser. + * @see http://ourcodeworld.com/projects/projects-documentation/15/read-doc/artyom-initialize/artyom-js + * @param {ArtyomConfigProperties} config + * @returns {Boolean} + */ + initialize(config: ArtyomConfigProperties): boolean; + + /** + * Force artyom to stop listen even if is in continuos mode. + * @see http://ourcodeworld.com/projects/projects-documentation/9/read-doc/artyom-fatality/artyom-js + * @returns {Boolean} + */ + fatality(): boolean; + + /** + * Add dinamically commands to artyom using. You can even add commands while artyom is active. + * @see http://ourcodeworld.com/projects/projects-documentation/4/read-doc/artyom-addcommands/artyom-js + * @param {ArtyomCommand | Array[ArtyomCommand]} newCommand + * @returns {Boolean} + */ + addCommands(newCommand: ArtyomCommand | ArtyomCommand[]): boolean; + + /** + * Remove the commands of artyom with indexes that matches with the given text. + * @see http://ourcodeworld.com/projects/projects-documentation/19/read-doc/artyom-removecommands/artyom-js + * @param {string} identifier + * @returns {Array} + */ + removeCommands(identifier: string): number[]; + + /** + * Removes all the added commands of artyom. + * @see http://ourcodeworld.com/projects/projects-documentation/7/read-doc/artyom-emptycommands/artyom-js + * @returns {Array} + */ + emptyCommands(): ArtyomCommand[]; + + /** + * Stops the actual and pendings messages that artyom have to say. + * @see http://ourcodeworld.com/projects/projects-documentation/23/read-doc/artyom-shutup/artyom-js + */ + shutUp(): void; + + /** + * Returns an object with the actual properties of artyom. + * @see http://ourcodeworld.com/projects/projects-documentation/12/read-doc/artyom-getproperties/artyom-js + * @returns {ArtyomConfigProperties} + */ + getProperties(): ArtyomConfigProperties; + + /** + * Create a listener when an artyom action is called. + * @see http://ourcodeworld.com/projects/projects-documentation/24/read-doc/artyom-when/artyom-js + */ + when(event: any, action: any): any; + + /** + * Returns the code language of artyom according to initialize function. + * @see http://ourcodeworld.com/projects/projects-documentation/11/read-doc/artyom-getlanguage/artyom-js + * @returns {String} Language + */ + getLanguage(): string; + + /** + * Talks a text according to the given parameters (private function). + * @param {String} text Text to be spoken + * @param {Int} actualChunk Number of chunk of the + * @param {Int} totalChunks + * @param {any} callbacks + */ + artyomTalk(text: any, actualChunk: any, totalChunks: any, callbacks: any): any; + + /** + * Splits a string into an array of strings with a limited size (chunk_length). + * @param {String} input text to split into chunks + * @param {Integer} chunk_length limit of characters in every chunk + */ + splitStringByChunks(input: any, chunk_length: any): string[]; + + /** + * Process the given text into chunks and execute the private function artyom_talk. + * @param {String} message Text to be spoken + * @param {Object} callbacks { onStart, onEnd } + * @see http://ourcodeworld.com/projects/projects-documentation/20/read-doc/artyom-say/artyom-js + */ + say(message: any, callbacks: any): void; + + /** + * Repeats the last sentence that artyom said. Useful in noisy environments. + * @param {Boolean} returnObject If set to true, an object with the text and the timestamp when was executed will be returned. + * @see http://ourcodeworld.com/projects/projects-documentation/25/read-doc/artyom-repeatlastsay/artyom-js + */ + repeatLastSay(returnObject: any): void; + + /** + * Verify if the browser supports speechSynthesis. + * @see http://ourcodeworld.com/projects/projects-documentation/40/read-doc/artyom-speechsupported/artyom-js + * @returns {Boolean} + */ + speechSupported(): boolean; + + /** + * Verify if the browser supports webkitSpeechRecognition. + * @see http://ourcodeworld.com/projects/projects-documentation/39/read-doc/artyom-recognizingsupported/artyom-js + * @returns {Boolean} + */ + recognizingSupported(): boolean; + + /** + * Simulate a voice command via JS. + * @see http://ourcodeworld.com/projects/projects-documentation/22/read-doc/artyom-simulateinstruction/artyom-js + * @param {string} sentence + * @returns {Boolean} + */ + simulateInstruction(sentence: string): boolean; + + /** + * Returns an object with data of the matched element. + * @param {string} voiceCommand + * @returns {Object | Function}. There is a result field when the function should return a boolean value. + */ + artyomExecute(voiceCommand: string): any; + + /** + * Displays a message in the console if the artyom propery DEBUG is set to true. + * @param {string} error The error to be debugged + * @param {string} traceLevel Error level: { error | warn | info } + * @see http://ourcodeworld.com/projects/projects-documentation/38/read-doc/artyom-debug/artyom-js + */ + debug(stringEvent: string, traceLevel: string): void; + + /** + * Allows to retrieve the recognized spoken text of artyom and do something with it everytime something is recognized. + * @param {Function} action + * @returns {Boolean} + */ + redirectRecognizedTextOutput(action: () => void): boolean; + + /** + * Says a random quote and returns it's object. + * @param data + */ + sayRandom(data: any): any; + + /** + * Artyom provide an easy way to create a dictation for your user. Just create an instance and start and stop when you want. + */ + newDictation(settings: any): any; + + /** + * A voice prompt will be executed. + */ + newPrompt(config: any): any; + + /** + * Artyom awaits for orders when this function is executed. If artyom gets a first parameter the instance will be stopped. + */ + artyomHey(): any; + + /** + * This function will return the webkitSpeechRecognition object used by artyom retrieve it only to debug on it or get some + * values, do not make changes directly. + */ + getNativeApi(): any; + + /** + * This function returns a boolean according to the SpeechRecognition status if artyom is listening, will return true. + * Note: This is not a feature of SpeechRecognition, therefore this value hangs on the fiability of the onStart and onEnd + * events of the SpeechRecognition + * @returns {Boolean} + */ + isRecognizing(): boolean; + + /** + * This function returns a boolean according to the speechSynthesis status if artyom is speaking, will return true. + * Note: This is not a feature of speechSynthesis, therefore this value hangs on the fiability of the onStart and onEnd + * events of the speechSynthesis. + * @returns {Boolean} + */ + isSpeaking(): boolean; + + /** + * The SpeechSynthesisUtterance objects are stored in the artyom_garbage_collector variable to prevent the wrong behaviour + * of artyom.say. Use this method to clear all spoken SpeechSynthesisUtterance unused objects. + * @returns {Boolean} + */ + clearGarbageCollection(): any; + + /** + * Returns the SpeechSynthesisUtterance garbageobjects. + */ + getGarbageCollection(): any; + + /** + * Pause the processing of commands. Artyom still listening in the background and it can be resumed after a couple of seconds. + * @returns {Boolean} + */ + dontObey(): any; + + /** + * Allow artyom to obey commands again. + * @returns {Boolean} + */ + obey(): any; + + /** + * A boolean to check if artyom is obeying commands or not. + * @returns {Boolean} + */ + isObeying(): boolean; + + /** + * Process the recognized text if artyom is active in remote mode. + * @returns {Boolean} + */ + remoteProcessorService(action: any): any; + + /** + * Returns a string with the actual version of Artyom script. + * @returns {String} + */ + getVersion(): string; + + /** + * Add commands like an artisan. If you use artyom for simple + * tasks then probably you don't like to write a lot to achieve it. + * Use the artisan syntax to write less, but with the same accuracy. + * @disclaimer Not a promise-based implementation, just syntax. + * @returns {Object} + */ + on(indexes: any, smart: any): any; + } + + /** + * ArtyomBuilder bla, bla... + */ + export class ArtyomBuilder { + /** + * Method to bla, bla, bla... + */ + static getInstance(): ArtyomJS + } + +} + +//tslint:disable-next-line:export-just-namespace +export = Artyom; +export as namespace Artyom; diff --git a/artyom.js/tsconfig.json b/artyom.js/tsconfig.json new file mode 100644 index 0000000000..631aed5bae --- /dev/null +++ b/artyom.js/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "artyom.js-tests.ts" + ] +} diff --git a/artyom.js/tslint.json b/artyom.js/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/artyom.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 4a723dcede4df6e08b030f36d8c9e182ae807bac Mon Sep 17 00:00:00 2001 From: jinho park Date: Wed, 18 Jan 2017 10:34:44 +0900 Subject: [PATCH 43/72] [juijs] update jui, jui-core, jui-grid library (#13806) * add jui-core * update index.d.ts for jui-core * update index.d.ts for jui * update index.d.ts for jui * update index.d.ts for jui-grid * update index.d.ts for jui-grid * fixed lint * fixed lint for jui-core and jui-grid * remove jquery.d.ts in tsconfig.json * update rule for lint * update rule for lint * fixed space-before-function-paren problems * update jui-core/index.d.ts --- jui-core/index.d.ts | 824 +++++++++++++++++++++ jui-core/jui-core-tests.ts | 15 + jui-core/tsconfig.json | 20 + jui-core/tslint.json | 1 + jui-grid/index.d.ts | 996 ++++++++++++++++++++++++++ jui-grid/jui-grid-tests.ts | 182 +++++ jui-grid/tsconfig.json | 20 + jui-grid/tslint.json | 1 + jui/index.d.ts | 1380 ++++++++++++++++++++++++++++++++++++ jui/jui-tests.ts | 124 ++++ jui/tsconfig.json | 20 + jui/tslint.json | 1 + 12 files changed, 3584 insertions(+) create mode 100644 jui-core/index.d.ts create mode 100644 jui-core/jui-core-tests.ts create mode 100644 jui-core/tsconfig.json create mode 100644 jui-core/tslint.json create mode 100644 jui-grid/index.d.ts create mode 100644 jui-grid/jui-grid-tests.ts create mode 100644 jui-grid/tsconfig.json create mode 100644 jui-grid/tslint.json create mode 100644 jui/index.d.ts create mode 100644 jui/jui-tests.ts create mode 100644 jui/tsconfig.json create mode 100644 jui/tslint.json diff --git a/jui-core/index.d.ts b/jui-core/index.d.ts new file mode 100644 index 0000000000..0f1184c0a3 --- /dev/null +++ b/jui-core/index.d.ts @@ -0,0 +1,824 @@ +// Type definitions for jui-core 2.0 +// Project: https://github.com/juijs/jui-core +// Definitions by: JinHo Park +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var jui: JuiStatic; + +interface UtilBase { + /** + * @property browser check browser agent + * @property {Boolean} browser.webkit Webkit 브라우저 체크 + * @property {Boolean} browser.mozilla Mozilla 브라우저 체크 + * @property {Boolean} browser.msie IE 브라우저 체크 */ + browser: { + webkit: boolean, + mozilla: boolean, + msie: boolean + }; + + /** + * @property {Boolean} isTouch + * check touch device + */ + isTouch: boolean; + + /** + * @method inherit + * + * 프로토타입 기반의 상속 제공 + * + * @param {Function} ctor base Class + * @param {Function} superCtor super Class + */ + inherit( ctor: ((...args: any[]) => any), superCtor: ((...args: any[]) => any) ): void; + + /** + * @method extend + * + * implements object extend + * + * @param {Object|Function} origin + * @param {Object|Function} add + * @param {Boolean} skip + * @return {Object} + */ + extend(origin: any, add: any, skip: boolean): any; + + /** + * convert px to integer + * @param {String or Number} px + * @return {Number} + */ + pxToInt(px: string| number): number; + + /** + * @method clone + * implements object clone + * @param {Array/Object} obj 복사할 객체 + * @return {Array} + */ + clone(obj: any): any[]; + + /** + * @method deepClone + * implements object deep clone + * @param obj + * @param emit + * @return {*} + */ + deepClone(obj: any, emit: any): any[]; + + /** + * @method sort + * use QuickSort + * @param {Array} array + * @return {QuickSort} + */ + sort(array: any[]): UtilQuickSort; + + /** + * @method runtime + * + * caculate callback runtime + * + * @param {String} name + * @param {Function} callback + */ + runtime(name: string, callback: ((...args: any[]) => void)): void; + + /** + * @method template + * parsing template string + * @param html + * @param obj + */ + template(html: string, obj?: any): ((obj: any) => string) | string; + + /** + * @method resize + * add event in window resize event + * @param {Function} callback + * @param {Number} ms delay time + */ + resize(callback: ((...args: any[]) => void), ms: number): void; + + /** + * @method index + * + * IndexParser 객체 생성 + * + * @return {KeyParser} + */ + index(): UtilKeyParser; + + /** + * @method chunk + * split array by length + * @param {Array} arr + * @param {Number} len + * @return {Array} + */ + chunk(arr: any[], len: number): any[]; + + /** + * @method typeCheck + * check data type + * @param {String} t type string + * @param {Object} v value object + * @return {Boolean} + */ + typeCheck(typeName: string, value: any): boolean; + + + typeCheckObj(uiObj: any, list: any): void; + + /** + * @method dataToCsv + * + * data 를 csv 로 변환한다. + * + * @param {Array} keys + * @param {Array} dataList + * @param {Number} dataSize + * @return {String} 변환된 csv 문자열 + */ + dataToCsv(keys: string[] , dataList: any[], dataSize: number): string; + + /** + * @method dataToCsv2 + * + * @param {Object} options + * @return {String} + */ + dataToCsv2(options: any): string; + + /** + * @method fileToCsv + * + * file 에서 csv 컨텐츠 로드 + * + * @param {File} file + * @param {Function} callback + */ + fileToCsv(fileText: string, callback: ((data: any) => void)): void; + + /** + * @method csvToBase64 + * + * csv 다운로드 링크로 변환 + * + * @param {String} csv + * @return {String} data uri string + */ + csvToBase64(csv: string): string; + + /** + * @method csvToData + * + * @param {Array} keys + * @param {String} csv + * @param {Number} csvNumber + * @return {Array} + */ + csvToData(keys: string[], csv: string, csvNumber: number): any[]; + + /** + * @method getCsvFields + * + * csv 에서 필드 얻어오기 + * + * @param {Array} fields + * @param {Array} csvFields + * @return {Array} + */ + getCsvFields(fields: string[], csvFields: string[]): string[]; + + /** + * @method svgToBase64 + * + * xml 문자열로 svg datauri 생성 + * + * @param {String} xml + * @return {String} 변환된 data uri 링크 + */ + svgToBase64(xml: string): string; + + /** + * @method dateFormat + * + * implements date format function + * + * yyyy : 4 digits year + * yy : 2 digits year + * y : 1 digit year + * + * @param {Date} date + * @param {String} format date format string + * @param {Boolean} utc + * @return {string} + */ + dateFormat(date: Date, format: string, utc?: boolean): string; + + /** + * @method createId + * + * 유니크 아이디 생성 + * + * @param {String} key prefix string + * @return {String} 생성된 아이디 문자열 + */ + createId(key: string): string; + + /** + * @method btoa + * + * Base64 인코딩 + * + * @return {String} + */ + btoa(input: any): string; + + /** + * @method atob + * + * Base64 디코딩 + * + * @return {Any} + */ + atob(input: string): any; + + /** + * implement async loop without blocking ui + * + * @param {Number} total loop count + * @param {Object} context + * @returns {Function} + */ + timeLoop(total: number, context?: any): ((index: number) => void); + + /** + * @method loop + * + * 최적화된 루프 생성 (5단계로 나눔) + * + * @param {Number} total loop count + * @param {Object} [context=null] + * @return {Function} 최적화된 루프 콜백 (index, groupIndex 2가지 파라미터를 받는다.) + */ + loop(total: number, context?: any): ((index: number, groupIndex: number) => void ); + + /** + * @method loopArray + * + * 배열을 사용해서 최적화된 루프로 생성한다. + * + * + * @param {Array} data 루프로 생성될 배열 + * @param {Object} [context=null] + * @return {Function} 최적화된 루프 콜백 (data, index, groupIndex 3가지 파라미터를 받는다.) + */ + loopArray(data: any[], context?: any): ((data: any, index: number, groupIndex: number) => void ); + + /** + * @method makeIndex + * + * 배열의 키 기반 인덱스를 생성한다. + * + * 개별 값 별로 멀티 인덱스를 생성한다. + * + * @param {Array} data + * @param {String} keyField + * @return {Object} 생성된 인덱스 + */ + makeIndex(data: any[], keyField: string): any; + + /** + * @method startsWith + * Check that it matches the starting string search string. + * + * @param {String} string + * @param {String} searchString + * @param {Number} [position=0] + * @return {Number} position + */ + startsWith(str: string, searchString: string, position?: number): number; + + /** + * @method endsWith + * Check that it matches the end of a string search string. + * + * @param {String} string + * @param {String} searchString + * @return {Number} position + */ + endsWith(str: string, searchString: string, position?: number): number; + + inArray(target: any, list: any[]): number; + + + trim(text: string): string; + + ready: ((...args: any[]) => void); + + param(data: any): string; + + ajax(data: any): void; + + scrollWidth(): number; +} + +interface JuiStatic { + /** + * @method ready + * + * ready 타임에 실행될 callback 정의 + * + * @param {Function} callback + */ + ready(depends?: string[], callback?: (...args: any[]) => void): void; + + /** + * @method defineUI + * + * 사용자가 실제로 사용할 수 있는 UI 클래스를 정의 + * + * @param {String} name 모듈 로드와 상속에 사용될 이름을 정한다. + * @param {Array} depends 'define'이나 'defineUI'로 정의된 클래스나 객체를 인자로 받을 수 있다. + * @param {Function} callback UI 클래스를 해당 콜백 함수 내에서 클래스 형태로 구현하고 리턴해야 한다. + */ + defineUI(name: string, depends: string[], callback: () => void, parent?: string): void; + + /** + * @method define + * + * UI 클래스에서 사용될 클래스를 정의하고, 자유롭게 상속할 수 있는 클래스를 정의 + * + * @param {String} name 모듈 로드와 상속에 사용될 이름을 정한다. + * @param {Array} depends 'define'이나 'defineUI'로 정의된 클래스나 객체를 인자로 받을 수 있다. + * @param {Function} callback UI 클래스를 해당 콜백 함수 내에서 클래스 형태로 구현하고 리턴해야 한다. + * @param {String} parent 상속받을 클래스 + */ + define(name: string, depends: string[], callback: () => void, parent?: string): void; + + /** + * @method redefine + * + * UI 클래스에서 사용될 클래스를 정의하고, 자유롭게 상속할 수 있는 클래스를 정의 + * + * @param {String} name 모듈 로드와 상속에 사용될 이름을 정한다. + * @param {Array} depends 'define'이나 'defineUI'로 정의된 클래스나 객체를 인자로 받을 수 있다. + * @param {Function} callback UI 클래스를 해당 콜백 함수 내에서 클래스 형태로 구현하고 리턴해야 한다. + * @param {String} parent 상속받을 클래스 + */ + redefine(name: string, depends: string[], callback: () => void, parent?: string): void; + + /** + * define과 defineUI로 정의된 클래스 또는 객체를 가져온다. + * + * @param name 가져온 클래스 또는 객체의 이름 + * @return {*} + */ + include(name: string): any; + + /** + * define과 defineUI로 정의된 모든 클래스와 객체를 가져온다. + * + * @return {Array} + */ + includeAll(): any[]; + + /** + * @method add + * Adds a component object created + * + * @param {Object} ui UI instance + */ + add(uiIns: any): void; + + + /** + * @method emit + * Generates a custom event to an applicable component + * + * @param {String} key Selector or UI type + * @param {String} type Event type + * @param {Array} args Event arguments + */ + emit(key: string, type: string, args: any[]): void; + + /** + * @method get + * Gets a component currently created + * + * @param {Integer/String} key + * @returns {Object/Array} UI instance + */ + get(key: number|string): any; + + /** + * @method getAll + * Gets all components currently created + * + * @return {Array} UI instances + */ + getAll(): any[]; + + /** + * @method create + * It is possible to create a component dynamically after the ready point + * + * @param {String} type UI type + * @param {String/DOMElement} selector + * @param {Object} options + * @return {Object} + */ + create(type: string, selector: any, options?: {}): any; +} + +interface UICollection { + destroy(): void; +} + +interface UICore { + + tpl?: any; + + event?: any; + + root?: any; + + /** + * @method emit + * Generates a custom event. The first parameter is the type of a custom event. A function defined as an option or on method is called + * + * @param {String} type Event type + * @param {Function} args Event Arguments + * @return {Mixed} + */ + emit(type: string, args: () => void): any; + + /** + * @method on + * A callback function defined as an on method is run when an emit method is called + * + * @param {String} type Event type + * @param {Function} callback + */ + on(type: string, callback: () => void): void; + + /** + * @method off + * Removes a custom event of an applicable type or callback handler + * + * @param {String} type Event type + */ + off(type: string): void; + + /** + * @method addValid + * Check the parameter type of a UI method and generates an alarm when a wrong value is entered + * + * @param {String} name Method name + * @param {Array} params Parameters + */ + addValid(name: string, params: any[]): void; + + /** + * @method callBefore + * Sets a callback function that is called before a UI method is run + * + * @param {String} name Method name + * @param {Function} callback + * @return {Mixed} + */ + callBefore(name: string, callback: () => void): void; + + /** + * @method callAfter + * Sets a callback function that is called after a UI method is run + * + * @param {String} name Method name + * @param {Function} callback + * @return {Mixed} + */ + callAfter(name: string, callback: () => void): void; + + /** + * @method callDelay + * Sets a callback function and the delay time before/after a UI method is run + * + * @param {String} name Method name + * @param {Function} callback + */ + callDelay(name: string, callObj: () => void): void; + + /** + * @method setTpl + * Dynamically defines the template method of a UI + * + * @param {String} name Template name + * @param {String} html Template markup + */ + setTpl(name: string, html: string): void; + + /** + * @method setOption + * Dynamically defines the options of a UI + * + * @param {String} key + * @param {Mixed} value + */ + setOption(key: string, value: any): void; + + /** + * @method destroy + * Removes all events set in a UI obejct and the DOM element + * + */ + destroy(): void; +} + +//noinspection TypeScriptUnresolvedVariable +export interface UIEvent extends UICore { + + root?: any; + + /** + * @method find + * Get the child element of the root element + * + * @param {String/HTMLElement} Selector + * @returns {*|jQuery} + */ + find(selector: any): JQuery; +} + +export class ColorScale { + domain(color: string, color2: string): this; + ticks(max: number): this; +} + +export interface UtilColor { + /** + * @method format + * + * convert color to format string + * + * // hex + * color.format({ r : 255, g : 255, b : 255 }, 'hex') // #FFFFFF + * + * // rgb + * color.format({ r : 255, g : 255, b : 255 }, 'rgb') // rgba(255, 255, 255, 0.5); + * + * // rgba + * color.format({ r : 255, g : 255, b : 255, a : 0.5 }, 'rgb') // rgba(255, 255, 255, 0.5); + * + * @param {Object} obj obj has r, g, b and a attributes + * @param {"hex"/"rgb"} type format string type + * @returns {*} + */ + format(obj: any, type: string): string; + + /** + * @method scale + * + * get color scale + * + * var c = color.scale().domain('#FF0000', '#00FF00'); + * + * // get middle color + * c(0.5) == #808000 + * + * // get middle color list + * c.ticks(20); // return array , [startColor, ......, endColor ] + * + * @returns {func} scale function + */ + scale(): ColorScale; + + /** + * @method map + * + * create color map + * + * var colorList = color.map(['#352a87', '#0f5cdd', '#00b5a6', '#ffc337', '#fdff00'], count) + * + * @param {Array} color_list + * @param {Number} count a divide number + * @returns {Array} converted color list + */ + map(color_list: string[], count: number): string[]; + + /** + * @method rgb + * + * parse string to rgb color + * + * color.rgb("#FF0000") === { r : 255, g : 0, b : 0 } + * + * color.rgb("rgb(255, 0, 0)") == { r : 255, g : 0, b : } + * + * @param {String} str color string + * @returns {Object} rgb object + */ + rgb(str: string): any; + + /** + * @method HSVtoRGB + * + * convert hsv to rgb + * + * color.HSVtoRGB(0,0,1) === #FFFFF === { r : 255, g : 0, b : 0 } + * + * @param {Number} H hue color number (min : 0, max : 360) + * @param {Number} S Saturation number (min : 0, max : 1) + * @param {Number} V Value number (min : 0, max : 1 ) + * @returns {Object} + */ + HSVtoRGB(H: number, S: number, V: number): any; + + /** + * @method RGBtoHSV + * + * convert rgb to hsv + * + * color.RGBtoHSV(0, 0, 255) === { h : 240, s : 1, v : 1 } === '#FFFF00' + * + * @param {Number} R red color value + * @param {Number} G green color value + * @param {Number} B blue color value + * @return {Object} hsv color code + */ + RGBtoHSV(R: number, G: number, B: number): any; + + /** + * @method lighten + * + * rgb 컬러 밝은 농도로 변환 + * + * @param {String} color RGB color code + * @param {Number} rate 밝은 농도 + * @return {String} + */ + lighten(color: string, rate: number): string; + + /** + * @method darken + * + * rgb 컬러 어두운 농도로 변환 + * + * @param {String} color RGB color code + * @param {Number} rate 어두운 농도 + * @return {String} + */ + darken(color: string, rate: number): string; +} + +interface UtilBase64 { + encode(input: string): string; + decode(input: string): string; +} + +interface UtilKeyParser { + /** + * @method isIndexDepth + * + * @param {String} index + * @return {Boolean} + */ + isIndexDepth(index: string): boolean; + + /** + * @method getIndexList + * + * @param {String} index + * @return {Array} + */ + getIndexList(index: string): boolean; + + /** + * @method changeIndex + * + * + * @param {String} index + * @param {String} targetIndex + * @param {String} rootIndex + * @return {String} + */ + changeIndex(index: string, targetIndex: string, rootIndex: string): string; + + /** + * @method getNextIndex + * + * @param {String} index + * @return {String} + */ + getNextIndex(index: string): string; + + /** + * @method getParentIndex + * + * + * @param {String} index + * @returns {*} + */ + getParentIndex(index: string): string; +} + +interface UtilMath { + /** + * @method rotate + * + * 2d rotate + * + * @param {Number} x + * @param {Number} y + * @param {Number} radian roate 할 radian + * @return {Object} + * @return {Number} return.x 변환된 x + * @return {Number} return.y 변환된 y + * + */ + rotate(x: number, y: number, radian: number): any; + + resize(maxWidth: number, maxHeight: number, objectWidth: number, objectHeight: number): any; + + /** + * @method radian + * + * convert degree to radian + * + * @param {Number} degree + * @return {Number} radian + */ + radian(degree: number): number; + + /** + * @method degree + * + * convert radian to degree + * + * @param {Number} radian + * @return {Number} degree + */ + degree(radian: number): number; + + angle(x1: number, y1: number, x2: number, y2: number): number; + + /** + * @method interpolateNumber + * + * a, b 의 중간값 계산을 위한 callback 함수 만들기 + * + * @param {Number} a first value + * @param {Number} b second value + * @return {Function} + */ + interpolateNumber(a: number, b: number): () => void; + + // 중간값 round 해서 계산하기 + interpolateRound(a: number, b: number): () => void; + + round(num: number, fixed: number): number; + + plus(a: number, b: number): number; + + minus(a: number, b: number): number; + + multi(a: number, b: number): number; + + div(a: number, b: number): number; + + remain(a: number, b: number): number; + + /** + * 특정 구간의 값을 자동으로 계산 + * + * @param {Object} min + * @param {Object} max + * @param {Object} ticks + * @param {Object} isNice + */ + nice(min: number, max: number, ticks: number, isNice: boolean): any; + + matrix(a: T[], b: T[]): T[]; + + matrix3d(a: T[], b: T[]): T[]; + + inverseMatrix3d(a: any[]): any[]; + +} + +export interface UtilScaleOrdinal extends Function { + (x: number): number; + domain(values: any[]): UtilScaleOrdinal; + range(values: any[]): UtilScaleOrdinal; + rangePoints(interval: number, padding?: number): () => void; + rangeBands(interval: number, padding?: number, outerPadding?: number): () => void; + invert(x: number): number; +} + +export type UtilQuickSort = (array: number[], isClone: boolean) => this; diff --git a/jui-core/jui-core-tests.ts b/jui-core/jui-core-tests.ts new file mode 100644 index 0000000000..6cf8a82c98 --- /dev/null +++ b/jui-core/jui-core-tests.ts @@ -0,0 +1,15 @@ +/// + +import {jui, UtilColor, UtilBase} from "./index"; + +jui.ready(["util.color"], function(color: UtilColor) { + console.log(color.rgb("#ff0000")); +}); + +let _ : UtilBase = jui.include("util.base"); + +let str: string = "10"; +console.log(_.typeCheck("string", str)); + +let i: number = 10; +console.log(_.typeCheck("string", i)); diff --git a/jui-core/tsconfig.json b/jui-core/tsconfig.json new file mode 100644 index 0000000000..1971daae6a --- /dev/null +++ b/jui-core/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jui-core-tests.ts" + ] +} diff --git a/jui-core/tslint.json b/jui-core/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jui-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jui-grid/index.d.ts b/jui-grid/index.d.ts new file mode 100644 index 0000000000..0fee7cc271 --- /dev/null +++ b/jui-grid/index.d.ts @@ -0,0 +1,996 @@ +// Type definitions for jui-grid 2.0 +// Project: https://github.com/juijs/jui-grid +// Definitions by: Jin-Ho Park +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {UIEvent} from 'jui-core'; + +export interface GridColumn { + (index: number|string): this; + + /** @property {HTMLElement} [element=null] TH element of a specified column */ + element: any; + + /** @property {String} [order="asc"] Column sort state */ + order: "asc"|"desc"; + + /** @property {String} [name=null] Column name */ + name?: string; + + /** @property {Array} data Data from all rows belonging for a specified column */ + data: any[]; + + /** @property {Array} list TD element of all rows belonging to a specified column */ + list: any[]; + + /** @property {Integer} index Column index */ + index: number; + + /** @property {"show"/"hide"/"resize"} [type="show"] The current column state */ + type: "show"|"hide"|"resize"; + + /** @property {Integer} [width=null] Column width */ + width?: number; + + hide(): void; + show(): void; +} + +export interface GridRow { + /** @property {Array} data Data of a specifiedrow. */ + data: any[]; + + /** @property {Integer} seq Data of a sequence. */ + seq: number; + + /** @property {Integer} [rownum=null] The unique number of a child row under the specified parent row if a parent row exists. */ + rownum?: number; + + /** @property {String/Integer} [index=null] Index of a specified row. In the case of a tree structure, a depth is given. */ + index: number|string; + + /** @property {HTMLElement} [element=null] TR element of a specified row. */ + element: any; + + /** @property {Array} list List of TD elements of a specified row. */ + list: any[]; + + /** @property {Object} list List of hidden TD element. */ + hidden: {}; + + /** @property {uix.table.row} parent Variable that refers to the parent row. */ + parent?: GridRow; + + /** @property {Array} children List of child rows. */ + children: any[]; + + /** @property {Integer} [depth=0] The depth of the current row in the case of a tree structure. */ + depth: number; + + /** @property {"open"/"fold"} [type="fold"] State value that indicates whether a child row is shown or hidden. */ + type: "open"|"fold"; + + /** @property {Function} [type="null"] State value that indicates whether a child row is shown or hidden. */ + tpl?: () => void; + + setIndex(rownum: number|string): void; + reload(columns: GridColumn[], seq: any, xssFilter: any): void; + destroy(): void; + isLeaf(): boolean; + fold(): void; + open(): void; + appendChild(row: GridRow): void; + insertChild(rownum: number, row: GridRow, isReload?: any): void; + removeChild(index: number|string): void; + lastChild(): GridRow; + lastChildLeaf(lastRow: GridRow): GridRow|any; + showCell(index: number): void; + hideCell(index: number): void; +} + +export interface GridBase { + appendRow(index: number|string, data?: {}): GridRow; + insertRow(index: number|string, data: {}): GridRow; + updateRow(index: number|string, data: {}): GridRow; + moveRow(index: number|string, targetIndex: number|string): void; + removeRow(index: number|string): void; + openRow(index: number|string): void; + openRowAll(): void; + foldRow(index: number|string): void; + foldRowAll(): void; + removeRows(): void; + sortRows(name: string, isDesc: boolean): void; + appendColumn(tplType: string, dataList: any[]): void; + removeColumn(index: number|string): void; + hideColumn(index: number|string): void; + showColumn(index: number|string): void; + getColumnCount(): number; + getRowCount(): number; + getColumn(index?: number|string): GridColumn|GridColumn[]; + getRow(index?: number|string): GridRow|GridRow[]; + getRowAll(index: number|string): GridRow[]; + getRowParent(index: number|string): GridRow; + setColumn(index: number|string, column: GridColumn): void; + setRow(index: number|string, row: GridRow): void; +} + +export interface GridTable extends UIEvent { + (selector: any, options?: { + tpl?: any, + + event?: any, + /** + * @cfg {Array} [fields=null] + * Sets the name of columns in the order of being displayed on the table screen. + */ + fields?: any[], + + /** + * @cfg {Array} [csv=null] + * Sets the column key shown when converted to a CSV string. + */ + csv?: any[], + + /** + * @cfg {Array} [csvNames=null] + * Sets the name of a column shown when converting to a CSV string, which must be defined in the same order as the CSV option. + */ + csvNames?: any[], + + /** + * @cfg {Array} [csvNumber=null] + * Sets the column key to be changed to a number form when converted to a CSV string. + */ + csvNumber?: any[], + + /** + * @cfg {Array} data + * Sets the initial row list of a table. + */ + data?: any[], + + /** + * @cfg {Boolean/Array} [colshow=false] + * Sets a column index shown when the Show/Hide Column menu is enabled. + */ + colshow?: boolean|any[], + + /** + * @cfg {Boolean} [scroll=false] + * Determines whether to use a table scroll. + */ + scroll?: boolean, + + /** + * @cfg {Integer} [scrollHeight=200] + * Sets the reference height of a body area when using a table scroll. + */ + scrollHeight?: number, + + /** + * @cfg {Integer} [width=0] + * Sets the area of a table. + */ + width?: number, + + /** + * @cfg {Boolean} [expand=false] + * Determines whether to use an extended row area. + */ + expand?: boolean, + + /** + * @cfg {Boolean} [expandEvent=true] + * Sets the Show/Hide state of an extended row area when clicking on a row. + */ + expandEvent?: boolean, + + /** + * @cfg {Boolean|Array} [editRow=false] + * Determines whether to use a modified row area. + */ + editRow?: boolean|any[], + + /** + * @cfg {Boolean} [editEvent=true] + * Sets the Show/Hide state of an extended row area when doubleclicking on a row/cell. + */ + editEvent?: boolean, + + /** + * @cfg {Boolean} [resize=false] + * Determines whether to use the column resizing function. + */ + resize?: boolean, + + /** + * @cfg {Boolean/Array} [sort=false] + * Determines whether to use the table sort function. + */ + sort?: boolean|any[], + + /** + * @cfg {Integer} [sortIndex=null] + * Determines whether to use the table sort function. + */ + sortIndex?: number, + + /** + * @cfg {String} [sortOrder="asc"] + * Determines whether to use the table sort function. + */ + sortOrder?: "asc"|"desc", + + /** + * @cfg {Boolean} [sortEvent=true] + * Determines whether to use the sort function when you click on a column. + */ + sortEvent?: boolean, + + /** + * @cfg {Boolean} [moveRow=false] + * Determines whether to use the move function when you fire row draggable event. + */ + moveRow?: boolean, + + }): this; + + root?: any; + + /** + * @method update + * Updates the list of rows or modifies the row at a specified index. + * + * @param {Array} rows + */ + update(indexOrRows?: any, rows?: any): void; + /** + * @method updateTree + * It is possible to configure a tree table using an object array with the index and data properties. + * + * @param {Array} rows + */ + updateTree(rows: any[]): void; + + /** + * @method append + * Add a row or a child row to at a specified index. + * + * @param {RowObject} row + */ + append(rowOrIndex?: number|any, row?: any): void; + + /** + * @method insert + * Adds a row at a specified index. + * + * @param {Integer} index + * @param {RowObject} row + */ + insert(index: number, dataList: {}): void; + + /** + * @method select + * Adds a selected class to a row at a specified index and gets an instance of the applicable row. + * + * @param {Integer} index + * @return {RowObject} row + */ + select(index: number): GridRow; + + /** + * @method unselect + * Removes a selected class from a selected row and gets an instance of the row in question. + * + * @return {RowObject} row + */ + unselect(): GridRow; + + /** + * @method check + * Add a checked class to a row at a specified index. + * + * @param {Integer} index + */ + check(index: number): void; + + /** + * @method uncheck + * Removes a checked class from a row at a specified index. + * + * @param {Integer} index + */ + uncheck(index: number): void; + + /** + * @method uncheckAll + * Removes checked classes from all rows. + */ + uncheckAll(): void; + + /** + * @method remove + * Remove a row at a specified index. + * + * @param {Integer} index + */ + remove(index: number): void; + + /** + * @method reset + * Removes all rows. + */ + reset(): void; + + /** + * @method move + * Moves a row iat a specified index to the target index. + * + * @param {Integer} index + * @param {Integer} targetIndex + */ + move(index: number, targetIndex: number): void; + + /** + * @method sort + * Moves a row iat a specified index to the target index. + * + * @param {Integer} index + * @param {String} order "asc" or "desc" + */ + sort(index: number, order: string, e?: any): void; + + /** + * @method scroll + * Sets the scroll based on the height of a table. + * + * @param {Integer} height + */ + scroll(height: number): void; + + /** + * @method open + * Shows a child row of a specified index. + * + * @param {Integer} index + */ + open(index: number): void; + + /** + * @method fold + * Hides a child row of a specified index. + * + * @param {Integer} index + */ + fold(index: number): void; + + /** + * @method openAll + * Shows all child rows of a specified index. + */ + openAll(): void; + + /** + * @method foldAll + * Hides all child rows of a specified index. + */ + foldAll(): void; + + /** + * @method resize + * Resets the inner scroll and columns of a table. + */ + resize(): void; + + /** + * @method resizeColumns + * Resets the sizes of all columns of a table. + */ + resizeColumns(): void; + + /** + * @method size + * Gets the size of all the rows of a table. + * + * @return {Integer} size + */ + size(): number; + + /** + * @method count + * Gets the number of trows of a table. + * + * @return {Integer} count + */ + count(): number; + + /** + * @method list + * Gets all the rows of a table. + * + * @return {Array} rows + */ + list(): GridRow[]; + + /** + * @method listData + * Gets the data of all the rows of a table. + * + * @return {Array} datas + */ + listData(): any[]; + + /** + * @method listAll + * Gets all the rows of a table including child rows. + * + * @return {Array} rows + */ + listAll(): GridRow[]; + + /** + * @method listChecked + * Gets all rows in a check state. + * + * @return {Array} rows + */ + listChecked(): GridRow[]; + + /** + * @method listColumn + * Gets all columns. + * + * @return {Array} columns + */ + listColumn(): GridColumn; + + /** + * @method get + * Gets the row at the specified index. + * + * @param {Integer} index + * @return {RowObject} row + */ + get(index: number): GridRow; + + /** + * @method getAll + * Gets all rows of at the specified index including child rows. + * + * @param {Integer} index + * @return {Array} rows + */ + getAll(index: number): GridRow[]; + + /** + * @method getColumn + * Gets the column at the specified index. + * + * @param {"Integer"/"String"} key index or column key + * @return {ColumnObject} column + */ + getColumn(index: number|string): GridColumn; + + /** + * @method showColumn + * Shows the column index (or column name). + * + * @param {"Integer"/"String"} key index or column name + */ + showColumn(index: number|string, e?: any): void; + + /** + * @method hideColumn + * Hides the column index (or column name). + * + * @param {"Integer"/"String"} key index or column name + */ + hideColumn(index: number|string, e?: any): void; + + /** + * @method initColumns + * It is possible to determine the index or name of the column to be shown in an array. + * + * @param {"Integer"/"String"} key index or column name + */ + initColumns(keys: any): void; + + /** + * @method showColumnMenu + * Shows the Show/Hide Column menu at specified coordinates. + * + * @param {Integer} x + * @param {Integer} y + */ + showColumnMenu(x: number, y: number): void; + + /** + * @method hideColumnMenu + * Hides the Show/Hide Column menu. + */ + hideColumnMenu(): void; + + /** + * @method toggleColumnMenu + * Shows or hides the Show/Hide Column menu. + * + * @param {Integer} x + * @param {Integer} y + */ + toggleColumnMenu(x: number, y: number): void; + + /** + * @method showExpand + * Shows the extended row area of a specified index. + * + * @param {Integer} index + */ + showExpand(index: number, obj?: any, e?: any): void; + + /** + * @method hideExpand + * Hides the extended row area of a specified index. + */ + hideExpand(e?: any): void; + + /** + * @method getExpand + * Get a row in which the extended area is currently activated. + * + * @return {RowObject} row + */ + getExpand(): GridRow; + + /** + * @method showEditRow + * Shows the modified row area of a specified index. + * + * @param {Integer} index + */ + showEditRow(index: number, e?: any): void; + + /** + * @method hideEditRow + * Hides the modified row area of a specified index. + */ + hideEditRow(data?: any): void; + + /** + * @method getEditRow + * Get a row in which the modified area is currently activated. + * + * @return {RowObject} row + */ + getEditRow(): GridRow; + + /** + * @method setCsv + * Updates a table using a CVS string. + */ + setCsv(csvOrKey: any, key?: any): void; + + /** + * @method setCsvFile + * Updates a table using a CVS file. + */ + setCsvFile(fileOrKey: any, key?: any): void; + + /** + * @method getCsv + * Gets the data of a table as a CSV string. + * + * @param {Boolean} isTree + * @return {String} csv + */ + getCsv(isTree: boolean): string; + + /** + * @method getCsvBase64 + * Gets the data of a table as a CSV string encoded as base64. + * + * @param {Boolean} isTree + * @return {String} base64 + */ + getCsvBase64(isTree: boolean): string; + + /** + * @method downloadCsv + * Downloads the data of a table as a CSV file. + * + * @param {String} name + * @param {Boolean} isTree + */ + downloadCsv(name: string, isTree: boolean): void; + + /** + * @method activeIndex + * Gets the index of a row that is activated in an extended/modified/selected state. + * + * @return {Integer} index + */ + activeIndex(): number; +} + +export interface GridXTable extends UIEvent { + (selector: any, options?: { + + }): this; + + render(isTree?: boolean): void; + + /** + * @method select + * Adds a selected class to a row at a specified index and gets an instance of the applicable row. + * + * @param {Integer} index + * @return {RowObject} row + */ + select(index: number): GridRow; + + /** + * @method unselect + * Removes a selected class from a selected row and gets an instance of the row in question. + * + * @return {RowObject} row + */ + unselect(): GridRow; + + /** + * @method update + * Updates the list of rows or modifies the row at a specified index. + * + * @param {Array} rows + */ + update(dataList: any[]): void; + + /** + * @method updateTree + * It is possible to configure a tree table using an object array with the index and data properties. + * + * @param {Array} rows + */ + updateTree(tree: any[]): void; + + /** + * @method append + * Add a row or a child row to at a specified index. + * + * @param {RowObject} row + * @param {RowObject} row + */ + append(index: number, data: {}): void; + /** + * @method open + * Shows a child row of a specified index. + * + * @param {Integer} index + */ + open(index: number|string): void; + + /** + * @method fold + * Hides a child row of a specified index. + * + * @param {Integer} index + */ + fold(index: number|string): void; + + /** + * @method openAll + * Shows all child rows of a specified index. + */ + openAll(index: number|string): void; + + /** + * @method foldAll + * Hides all child rows of a specified index. + */ + foldAll(index: number|string): void; + + /** + * @method next + * Changes to the next page. + */ + next(): void; + + /** + * @method page + * Changes to the page of at a specified index. + * + * @param {Integer} index + */ + page(pNo: number): void; + + /** + * @method sort + * Moves a row iat a specified index to the target index. + * + * @param {Integer} index + * @param {String} order "asc" or "desc" + */ + sort(index: number, order: "asc"|"desc", e?: any, isNotLoading?: any): void; + + /** + * @method filter + * Filters columns at a specified to locate rows that contain keywords in the cell value. + * + * @param {Function} callback + */ + filter(callback: (data: any) => void): void; + + /** + * @method rollback + * Returns filtered rows to the original state. + */ + rollback(): void; + + /** + * @method clear + * Remove all row elements. + */ + clear(): void; + + /** + * @method clear + * Remove all data + */ + reset(): void; + + /** + * @method resize + * Resets the inner scroll and columns of a table. + */ + resize(): void; + + /** + * @method scrollWidth + * Sets the scroll based on the width of a table. + * + * @param {Integer} width + */ + scrollWidth(scrollWidth: number, isInit?: boolean): void; + + /** + * @method scrollHeight + * Sets the scroll based on the height of a table. + * + * @param {Integer} height + */ + scrollHeight(h: number): void; + + /** + * @method scrollTop + * Sets the scroll based on the height of a table. + * + * @param {Integer|String} index + * @param {Integer} dist + */ + scrollTop(index: number|string, dist: number): void; + + /** + * @deprecated + * @method height + * Sets the scroll based on the height of a table. + * + * @param {Integer} height + */ + height(h: number): void; + + /** + * @method size + * Gets the size of all the rows of a table. + * + * @return {Integer} size + */ + size(): number; + + /** + * @method count + * Gets the number of trows of a table. + * + * @return {Integer} count + */ + count(): number; + + /** + * @method list + * Gets all the rows of a table. + * + * @return {Array} rows + */ + list(): GridRow[]; + + /** + * @method listColumn + * Gets all columns. + * + * @return {Array} columns + */ + listColumn(): GridColumn[]; + + /** + * @method listData + * Gets the data of all the rows of a table. + * + * @return {Array} datas + */ + listData(): any[]; + + /** + * @method get + * Gets the row at the specified index. + * + * @param {Integer|String} index + * @return {RowObject} row + */ + get(index: number): GridRow; + + getAll(index: number, _result?: any): GridRow[]; + + /** + * @method getColumn + * Gets the column at the specified index. + * + * @param {"Integer"/"String"} key index or column key + * @return {ColumnObject} column + */ + getColumn(index: number|string): GridColumn; + + /** + * @method getData + * Gets the data at the specified index. + * + * @param {"Integer"/"String"} key index + * @return {ColumnObject} data + */ + getData(index: number|string): any; + + /** + * @method showColumn + * Shows the column index (or column name). + * + * @param {"Integer"/"String"} key index or column name + */ + showColumn(index: number|string): void; + + /** + * @method hideColumn + * Hides the column index (or column name). + * + * @param {"Integer"/"String"} key index or column name + */ + hideColumn(index: number|string): void; + + /** + * @method initColumns + * It is possible to determine the index or name of the column to be shown in an array. + * + * @param {"Integer"/"String"} key index or column name + */ + initColumns(keys: number|string): void; + + /** + * @method showColumnMenu + * Shows the Show/Hide Column menu at specified coordinates. + * + * @param {Integer} x + * @param {Integer} y + */ + showColumnMenu(x: number, y: number): void; + + /** + * @method hideColumnMenu + * Hides the Show/Hide Column menu. + */ + hideColumnMenu(): void; + + /** + * @method toggleColumnMenu + * Shows or hides the Show/Hide Column menu. + * + * @param {Integer} x + * @param {Integer} y + */ + toggleColumnMenu(x: number, y: number): void; + + /** + * @method showExpand + * Shows the extended row area of a specified index. + * + * @param {Integer} index + */ + showExpand(index: number, obj: any): void; + + /** + * @method hideExpand + * Hides the extended row area of a specified index. + */ + hideExpand(index: number): void; + + /** + * @method getExpand + * Get a row in which the extended area is currently activated. + * + * @return {RowObject} row + */ + getExpand(): GridRow; + + /** + * @method showLoading + * Shows the loading screen for the specified delay time. + * + * @param {Integer} delay + */ + showLoading(delay: number): void; + + /** + * @method hideLoading + * Hides the loading screen. + */ + hideLoading(): void; + + /** + * @method setCsv + * Updates a table using a CVS string. + */ + setCsv(csv: string): void; + + /** + * @method setCsvFile + * Updates a table using a CVS file. + */ + setCsvFile(file: any): void; + + /** + * @method getCsv + * Gets the data of a table as a CSV string. + * + * @param {Boolean} isTree + * @return {String} csv + */ + getCsv(): string; + + /** + * @method getCsvBase64 + * Gets the data of a table as a CSV string encoded as base64. + * + * @param {Boolean} isTree + * @return {String} base64 + */ + getCsvBase64(): string; + + /** + * @method downloadCsv + * Downloads the data of a table as a CSV file. + * + * @param {String} name + * @param {Boolean} isTree + */ + downloadCsv(name: string): void; + + /** + * @method rowFunc + * Ir is possible to use a function for all row data applicable to the column (or column name) of a specified column (or column name). Currently only SUM and AVG are supported. + * + * @param {"sum"/"svg"} funcType + * @param {Integer} columnIndex + * @param {Function} callback + */ + rowFunc(type: "sum"|"avg", index: number, callback: (data: any) => void): any; + + /** + * @method getPage + * Gets the current page of a table. + * + * @return {Integer} page + */ + getPage(): number; + + /** + * @method activeIndex + * Gets the index of a row that is activated in an extended/modified/selected state. + * + * @return {Integer} index + */ + activeIndex(): number; +} diff --git a/jui-grid/jui-grid-tests.ts b/jui-grid/jui-grid-tests.ts new file mode 100644 index 0000000000..1d29dd059b --- /dev/null +++ b/jui-grid/jui-grid-tests.ts @@ -0,0 +1,182 @@ +/// + +import {jui} from 'jui-core'; +import {GridTable, GridXTable, GridRow} from "./index"; + + +jui.ready([ "grid.table" ], function(table: GridTable) { + let table_1: GridTable = table("#table_1", { + data: [ + { name: "Hong", age: "20", location: "Ilsan" }, + { name: "Jung", age: "30", location: "Seoul" }, + { name: "Park", age: "15", location: "Yeosu" }, + { name: "Kang", age: "32", location: "Seoul" }, + { name: "Song", age: "12", location: "Gwangju" }, + { name: "Yoon", age: "22", location: "Damyang" }, + { name: "Kim", age: "33", location: "Busan" }, + { name: "Hwang", age: "21", location: "Seoul" } + ] + }); + + table_1.scroll(100); +}); + +jui.ready([ "grid.table" ], function(table: GridTable) { + let table_3:GridTable = table("#table_3", { + event: { + expand: function(row: any, e: any): void { + $(row.list[0]).html(""); + }, + expandend: function(row: any, e: any): void { + $(row.list[0]).html(""); + } + }, + expand: true + }); + + table_3.update([ + { name: "Hong", age: "20", location: "Ilsan" }, + { name: "Jung", age: "30", location: "Seoul" }, + { name: "Park", age: "10", location: "Dangjin" } + ]); + + let table_3_submit: Function = function(index: number) { + var name = $(table_3.root).find(".name").val(), + age = $(table_3.root).find(".age").val(), + location = $(table_3.root).find(".location").val(); + + //noinspection TypeScriptValidateTypes + table_3.update(index, { name: name, age: age, location: location }); + table_3.hideExpand(); + } +}); + +jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { + var page = 1; + + let xtable_2: GridXTable = xtable("#xtable_2", { + fields: [ "name", "age", "location" ], + resize: true, + sort: true, + buffer: "page", + bufferCount: 20 + }); + + let xtable_2_submit: Function = function() { + var result: any[] = []; + + for(var i = 0; i < 1000000; i++) { + result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); + } + + page = 1; + xtable_2.update(result); + xtable_2.resize(); + } + + let xtable_2_page: Function = function(no: number) { + page += no; + page = (page < 1) ? 1 : page; + xtable_2.page(page); + } +}); + + +jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { + let xtable_4:GridXTable = xtable("#xtable_4", { + fields: [ "name", "age", "location" ], + data: [ + { name: "Hong", age: "20", location: "Ilsan" }, + { name: "Jung", age: "30", location: "Seoul" }, + { name: "Park", age: "10", location: "Dangjin" } + ], + resize: true, + sort: true, + buffer: "s-page", + bufferCount: 20 + }); + + let xtable_4_submit: Function = function(isMulti: boolean) { + if(isMulti) { + xtable_4.filter(function(data: any) { + if(data.age >= 30 || data.name.indexOf("ng") != -1) { + return true; + } + }); + } else { + xtable_4.filter(function(data: any) { + if(data.location.indexOf("eo") != -1) { + return true; + } + }); + } + } +}); + +jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { + let xtable_6: GridXTable = xtable("#xtable_6", { + fields: [ "name", "age", "location" ], + resize: true, + sort: true, + width: 800, + scrollWidth: 600, + scrollHeight: 400, + rowHeight: 26, + buffer: "vscroll", + tpl: { + row: "", + none: "Data does not exist." + } + }); + + let xtable_6_submit: Function = function() { + var result: any[] = []; + + for(var i = 0; i < 1000000; i++) { + result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); + } + + xtable_6.update(result); + } +}); + +jui.ready([ "grid.xtable" ], function(xtable: GridXTable) { + let xtable_8: GridXTable = xtable("#xtable_8", { + fields: [ "url", "count" ], + resize: true, + buffer: "vscroll", + rowHeight: 27, + scrollHeight: 300, + tpl: { + row: $("#tpl_row").html(), + none: $("#tpl_none").html() + }, + event: { + select: function(row: GridRow, e:any) { + if(row.type == "fold") { + xtable_8.open(row.index); + } else { + xtable_8.fold(row.index); + } + } + } + }); + + xtable_8.updateTree([ + { index: "0", type: "open", data: { url: "/", count: 105 } }, + { index: "0.0", type: "fold", data: { url: "/css", count: 35 } }, + { index: "0.0.0", type: "fold", data: { url: "/index.css", count: 15 } }, + { index: "0.0.1", type: "fold", data: { url: "/layout.css", count: 15 } }, + { index: "0.0.2", type: "fold", data: { url: "/login.css", count: 5 } }, + { index: "0.1", type: "fold", data: { url: "/js", count: 35 } }, + { index: "0.1.0", type: "fold", data: { url: "/index.js", count: 23 } }, + { index: "0.1.1", type: "fold", data: { url: "/jquery.js", count: 12 } }, + { index: "0.2", type: "fold", data: { url: "/img", count: 0 } }, + { index: "0.2.0", type: "fold", data: { url: "logo.ico", count: 0 } }, + { index: "0.3", type: "fold", data: { url: "/main.jsp", count: 10 } }, + { index: "0.4", type: "fold", data: { url: "/login.jsp", count: 10 } }, + { index: "0.5", type: "fold", data: { url: "/sitemap.xml", count: 10 } }, + { index: "0.6", type: "fold", data: { url: "/package.json", count: 5 } } + ]); + +}); diff --git a/jui-grid/tsconfig.json b/jui-grid/tsconfig.json new file mode 100644 index 0000000000..8ae735866e --- /dev/null +++ b/jui-grid/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jui-grid-tests.ts" + ] +} diff --git a/jui-grid/tslint.json b/jui-grid/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jui-grid/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/jui/index.d.ts b/jui/index.d.ts new file mode 100644 index 0000000000..c1dec57e39 --- /dev/null +++ b/jui/index.d.ts @@ -0,0 +1,1380 @@ +// Type definitions for jui 2.0 +// Project: https://github.com/juijs/jui#readme +// Definitions by: Jin-Ho Park +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {UIEvent} from 'jui-core'; + +export interface UIAccordion extends UIEvent { + + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {Integer} [index=null] + * Sets an enabled node + */ + index?: number, + + /** + * @cfg {Boolean} [autoFold=false] + * When you click on a node, the node folding + */ + autoFold?: boolean, + + /** + * @cfg {Boolean} [multipanel=false] + * + */ + multipanel?: boolean + }) : this; + + /** + * @method activeIndex + * Gets the index of the currently enabled node + * + * @return {Integer} Index + */ + activeIndex(): number; +} + +export interface UIAutoComplete { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {String/DOMElement} [target=null] + * Designates a target selector when an autofill route is not a target + */ + target?: any, + + /** + * @cfg {Array} words + * Designates words subject to autofill + */ + words?: string[] + }) : this; + + /** + * @method update + * Updates words subject to autofill + * + * @param {Array} words + * + */ + update(newWords: string[]): void; + + /** + * @method close + * Close the active drop-down + * + */ + close(): void; + + /** + * @method list + * Gets filtered words subject to autofill + * + * @return {Array} words + */ + list(): string[]; +} + +export interface UIColorPicker { + (selector: any, options?: { + tpl?: any, + event?: any, + type?: string, + color?: string + }) : this; + + getColor(type: string): string|{}; + + setColor(value: string|{}): void; + +} + + +export interface UICombo { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {Integer} [index=0] + * Determines an initial selection button with a specified index + */ + index?: number, + + /** + * @cfg {String} [value=0] + * Determines an initial selection button with a specified value + */ + value?: string, + + /** + * @cfg {Integer} [width=0] + * Determines the horizontal size of a combo box + */ + width?: number, + + /** + * @cfg {Integer} [height=100] + * Determines an initial selection button with a specified value + */ + height?: number, + + /** + * @cfg {Boolean} [keydown=false] + * It is possible to select a node using the keyboard + */ + keydown?: boolean, + + /** + * @cfg {"top"/"bottom"} [position="bottom"] + * It is possible to determine an initial selection button with a specified value + */ + position?: "top"|"bottom", + + /** + * @cfg {Boolean} [flex=true] + * Drop-down menu is varied by changing the width function + */ + flex?: boolean + }) : this; + + /** + * @method setIndex + * Selects a button of a specified index + * + * @param {Number} index + */ + setIndex(index: number): void; + + /** + * @method setValue + * Selects a button having a specified value + * + * @param {Mixed} value + */ + setValue(value: any): void; + + /** + * @method getData + * Gets the data of the button currently selected + * + * @return {Object} + */ + getData(): {}; + + /** + * @method getValue + * Gets the value of the button currently selected + * + * @return {Mixed} + */ + getValue(): any; + + /** + * @method getText + * Gets the markup text of the button currently selected + * + * @return {String} + */ + getText(): string; + + /** + * @method open + * Shows the element list of a combo box + */ + open(e: any): void; + + /** + * @method fold + * Hides the element list of a combo box + */ + fold(): void; + + /** + * @method reload + * Re-defines a combo box + */ + reload(): void; +} + + +export interface UIDatePicker { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {"daily"/"monthly"/"yearly"} [type="daily"] + * Determines the type of a calendar + */ + type?: "daily"|"monthly"|"yearly", + + /** + * @cfg {String} [titleFormat="yyyy.MM"] + * Title format of a calendar + */ + titleFormat?: string, + + /** + * @cfg {String} [format="yyyy-MM-dd"] + * Format of the date handed over when selecting a specific date + */ + format?: string, + + /** + * @cfg {Date} [date="now"] + * Selects a specific date as a basic + */ + date?: "now"|Date, + + /** + * @cfg {Date} [minDate="null"] + * Selects a specific minimum date + */ + minDate?: Date, + + /** + * @cfg {Date} [maxDate="null"] + * Selects a specific maximum date + */ + maxDate?: Date + }) : this; + + /** + * @method page + * Outputs a calendar that fits the year/month entered + * + * @param {Integer} year + * @param {Integer} month + */ + page(y: number, m: number): void; + + /** + * @method prev + * Outputs a calendar that fits the previous year/month + * + */ + prev(e: any, moveYear?: boolean): void; + + /** + * @method next + * Outputs a calendar that fits the next year/month + * + */ + next(e: any, moveYear?: boolean): void; + + /** + * @method select + * Selects today if there is no value, or selects a date applicable to a timestamp or year/month/date + * + * @param {"year"/"month"/"date"/"timestamp"/"Date"} + */ + select( ...args: any[]): void; + + /** + * @method addTime + * Selects a date corresponding to the time added to the currently selected date + * + * @param {"Integer"/"Date"} time Timestamp or Date + */ + addTime(time: number|Date): void; + + /** + * @method getDate + * Gets the value of the date currently selected + * + * @return {Date} Date object + */ + getDate(): Date; + + /** + * @method getTime + * Gets the timestamp value of the date currently selected + * + * @return {Integer} Timestamp + */ + getTime(): number; + + /** + * @method getFormat + * Gets a date string that fits the format entered + * + * @return {String} format Formatted date string + */ + getFormat(format: string): string; + + /** + * @method reload + * Reloads the datepicker + */ + reload(): void; +} + +export interface UIDropdown { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {Boolean} [close=true] + * Closes the Auto when clicking on the dropdown list + */ + close?: boolean, + + /** + * @cfg {Boolean} [keydown=false] + * It is possible to choose anything on the dropdown list with the arrow keys on the keyboard + */ + keydown?: boolean, + + /** + * @cfg {Integer} [left=0] + * Sets the X coordinate of the dropdown list + */ + left?: number, + + /** + * @cfg {Integer} [top=0] + * Sets the Y coordinate of the dropdown list + */ + top?: number, + + /** + * @cfg {Integer} [width=0] + * Determines the horizontal size of a dropdown list + */ + width?: number, + + /** + * @cfg {Integer} [height=0] + * Determines the vertical size of a dropdown list + */ + height?: number, + + /** + * @cfg {Array} nodes + * Sets a dropdown list to data rather than markup + */ + nodes?: any[] + }): this; + + /** + * @method update + * Changes the dropdown list + * + * @param {Array} nodes Dropdown list + */ + update(nodes: any[]): void; + + /** + * @method hide + * Hides the dropdown + */ + hide(): void; + + /** + * @method show + * Shows a dropdown at the specified coordinates + * + * @param {Integer} x + * @param {Integer} y + */ + show(x: number, y: number): void; + + /** + * @method move + * Moves a dropdown to the specified coordinates + * + * @param {Integer} x + * @param {Integer} y + */ + move(x: number, y: number): void; + + /** + * @method reload + * Reloads the dropdown list + */ + reload(): void; +} + + +export interface UIModal { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {"black"/"gray"} [color="black"] + * Determines the color of a modal + */ + color?: "black"|"gray", + + /** + * @cfg {Float} [opacity=0.4] + * Sets the transparency of a modal + */ + opacity?: number, + + /** + * @cfg {String/DOMElement} [target="body"] + * Sets a selector on which a modal is shown + */ + target?: string|any, + + /** + * @cfg {Integer} [index=0] + * Determines the sequence (index) of a modal + */ + index?: number, + + /** + * @cfg {Boolean} [clone=false] + * Copies an existing modal and shows it + */ + clone?: boolean, + + /** + * @cfg {Boolean} [autoHide=true] + * Automatically hides a modal when clicking on it + */ + autoHide?: boolean + }): this; + + /** + * @method hide + * Hides a modal + */ + hide(): void; + + /** + * @method show + * Shows a modal + */ + show(): void; + + /** + * @method resize + * Re-adjust the location of a modal + */ + resize(): void; +} + + +export interface UINotify { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {"top"/"top-lefet"/"top-right"/"bottom"/"bottom-left"/"bottom-right"} [position="top-right"] + * Designates the location where a notice message is added + */ + position?: "top"|"top-lefet"|"top-right"|"bottom"|"bottom-left"|"bottom-right", + + /** + * @cfg {Integer} [padding=12] + * Determines the margin value of a notice message (the margin value may be in object form rather than a numeric value) + */ + padding?: number, + + /** + * @cfg {Integer} [distance=5] + * Determines each margin value when there are multiple notice messages + */ + distance?: number, + + /** + * @cfg {Integer} [timeout=3000] + * Determines the duration for which a notice message is displayed (the message does not disappear when the value is 0) + */ + timeout?: number, + + /** + * @cfg {Integer} [showDuration=500] + * Determines the duration of an effect when a notice message is shown + */ + showDuration?: number, + + /** + * @cfg {Integer} [hideDuration=500] + * Determines the duration of an effect when a notice message disappears + */ + hideDuration?: number, + + /** + * @cfg {String} [showEasing="swing"] + * Determines an effect when a notice message is shown (see CSS3 specifications) + */ + showEasing?: string, + + /** + * @cfg {String} [hideEasing="linear"] + * Determines an effect when a notice message disappears (see CSS3 specifications) + */ + hideEasing?: string + }): this; + + /** + * @method add + * Adds a notice message. The value passed is the data object shown by the notice template + * + * @param {Object} data + * @param {Integer} timeout + */ + add(data: {}, timeout: number): void; + + /** + * @method reset + * Removes all notice messages that are enabled + */ + reset(): void; +} + +export interface UIPaging { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {Integer} [count=0] + * Total number of data records subject to paging) + */ + count?: number, + + /** + * @cfg {Integer} [pageCount=10] + * Number of data records per page + */ + pageCount?: number, + + /** + * @cfg {Integer} [screenCount=5] + * Number of pages shown on the paging screen + */ + screenCount?: number + }): this; + + /** + * @method reload + * Reloads the number of specified data records, or reloads the initially configured number of data records if there is no parameter + * + * @param {Integer} count Data total count + */ + reload(count: number): void; + + /** + * @method page + * Changes to a specified page number, and gets the currently enabled page number if there is no parameter + * + * @param {Integer} pNo Page number + */ + page(pNo: number): void; + + /** + * @method next + * Changes to the next page + */ + next(): void; + + /** + * @method prev + * Changes to the previous page + */ + prev(): void; + + /** + * @method first + * Changes to the first page + */ + first(): void; + + /** + * @method last + * Changes to the last page + */ + last(): void; +} + +export interface UIProgress { + (selector: any, options?: { + tpl?: any, + event?: any, + type?: "simple" | "flat", // simple or flat + orient?: "horizontal"|"vertical", // or vertical, + min?: number, + max?: number, + value?: number, + striped?: boolean, // or true + animated?: boolean // or true + }): this; + + setAnimated(isAnimated: boolean): void; + setStriped(isStriped: boolean): void; + setValue(v: number): void; + getValue(): number; + +} + +export interface UIProperty { + (selector: any, options?: { + tpl?: any, + event?: any, + sort?: string, // name, group, type + viewport?: string, + items?: any[] + }): this; + + loadItems(newItems: any[]): void; + + addItem(item: {}|any[]): void; + + // remove item by key or title + removeItem(item: {}): void; + + /** + * @method getGroupList + * + * get a list of group's title. + */ + getGroupList(): any[]; + + /** + * @method collapsed + * + * collapse group's children + * + * @param {String} id + */ + collapsed(id: string): void; + + /** + * @method expanded + * + * expand group's children + * + * @param {String} id + */ + expanded(id: string): void; + + /** + * @method getValue + * + * get a list of property's value + * + * @param {String} [key=null] if key is null, value is all properties. + */ + getValue(key?: string): {} | any[]; + + getDefaultValue(): any[]; + + initValue(obj: {}): void; + + /** + * @method getValue + * + * set a list of property's value + * + * @param {Object} obj + */ + setValue(obj: {}): void; + + findRender(key: string): any; + findItem(key: string): any; + updateValue(key: string, value: any): void; + getAllValue(key: string): any; + refreshValue($dom: any, newValue: any): void; +} + +export interface UISelect { + (selector: any, options?: { + tpl?: any, + event?: any, + items?: any[], + placeholder?: string, + align?: 'left'|'right', + valign?: 'top'|'bottom', + multi?: boolean + }): this; + + setValue(value: any|any[]): void; + getValue(): any| any[]; + setSelectedIndex(index: number): void; + getSelectedIndex(): number; + update(data: any[]): void; +} + +export interface UISlider { + (selector: any, options?: { + tpl?: any, + event?: any, + type?: "single"|"double", // or double + orient?: "horizontal"|"vertical", // or vertical, + min?: number, + max?: number, + step?: number, + from?: number, + to?: number, + tooltip?: boolean, + format?: string, + progress?: boolean + + }): this; + + /** + * @method setFromValue + * set FromHandle's value + * + * @param {Number} + */ + setFromValue(value: number): void; + + /** + * @method setToValue + * set ToHandle's value + * + * @param {Number} + */ + setToValue(value: number): void; + + /** + * @method getFromValue + * get FromHandle's value + * + * @return {Number} value + */ + getFromValue(): number; + + /** + * @method getToValue + * get ToHandle's value + * + * @return {Number} value + */ + getToValue(): number; + +} + + +export interface UISplitter { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {String} [splitterClass='ui-splitter'] + * set splitter's class for design + */ + splitterClass?: string, + + /** + * @cfg {String} [hideClass='hide'] + * set splitter's hide class for design + */ + hideClass?: string, + + /** + * @cfg {Number} [barSize=4] + * set splitter's bar size + */ + barSize?: number, + + /** + * @cfg {Object} [barStyle={}] + * set custom splitter bar style + */ + barStyle?: {}, + + /** + * @cfg {"vertical"/"horizontal"} [direction='vertical'] + * set bar's direction + */ + direction?: 'vertical'|'horizontal', + + /** + * @cfg {String/Number} [initSize='50%'] + * set first panel's default width or height + */ + initSize?: string|number, + + /** + * @cfg {Number/Array} [minSize=30] + * set panel's minimum width or height + * + * if minSize is number , minSize is conver to array + * + * minSize[0] is first panel's minimum size + * minSize[1] is second panel's minimum size + * + */ + minSize?: number|number[], + + /** + * @cfg {String} [items=[]] + * + * set items to placed in vertical or horizontal + * + * support max two times + * + */ + items?: any[], + + /** + * @cfg {Boolean} [fixed=false] + * + * if fixed is true, panels can not resize. + * + */ + fixed?: boolean + }): this; + + setDirection(d: 'horizontal' | 'vertical'): void; + + setInitSize(size: number): void; + setHide(index: number): void; + setShow(index: number): void; + toggle(index: number): void; +} + +export interface UISwitch { + (selector: any, options?: { + tpl?: any, + event?: any, + checked?: boolean, + toggleEvent?: string + }): this; + + getValue(): boolean; + + setValue(value: boolean): void; + + toggle(): void; +} + +export interface UITab { + + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {String/DOMElement} [target=""] + * Determines a selector in the area to become the content of a tab + */ + target?: string|any, + + /** + * @cfg {Integer} [index=0] + * Sets an enabled tab + */ + index?: number, + + /** + * @cfg {Boolean} [drag=false] + * Changes the tab location through dragging + */ + drag?: boolean, + + /** + * @cfg {Array} nodes + * Sets a tab list to data rather than markup + */ + nodes?: any[] + }): this; + /** + * @method update + * Changes the tab list + * + * @param {Array} nodes + */ + update(nodes: any[]): void; + + /** + * @method insert + * Adds a tab at a specified index + * + * @param {Integer} index + * @param {Object} node + */ + insert(index: number, node: {}): void; + + /** + * @method append + * Adds a tab to the last node + * + * @param {Object} node + */ + append(node: {}): void; + + /** + * @method prepend + * Adds a tab to the first node + * + * @param {Object} node + */ + prepend(node: {}): void; + + /** + * @method remove + * Removes a tab at a specified index + * + * @param {Integer} index + */ + remove(index: number): void; + + /** + * @method move + * Changes a specified tab to a tab at a target index + * + * @param {Integer} index + * @param {Integer} targetIndex + */ + move(index: number, targetIndex: number): void; + + /** + * @method show + * Enables the tab at a specified index + * + * @param {Integer} index + */ + show(index: number): void; + + /** + * @method enable + * Enables the tab at a specified index + * + * @param {Integer} index + */ + enable(index: number): void; + + /** + * @method disable + * Disables the tab at a specified index + * + * @param {Integer} index + */ + disable(index: number): void; + + /** + * @method activeIndex + * Gets the index of the currently enabled tab + * + * @return {Integer} + */ + activeIndex(): number; +} + +export interface UITooltip { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {String} [color="black"] + * Determines the color of a tooltip + */ + color?: string, + + /** + * @cfg {"top"/"bottom"/"left"/"right"} [position="top"] + * Determines the location where a tooltip is shown + */ + position?: "top"|"bottom"|"left"|"right", + + /** + * @cfg {Integer} [width=150] + * Determines the horizontal size of a tooltip + */ + width?: number, + + /** + * @cfg {"left"/"right"/"center"} [align="left"] + * Determines the alignment state inside a tooltip + */ + align?: "left"|"right"|"center", + + /** + * @cfg {Integer} [delay=0] + * Determines the event time when a tooltip is shown + */ + delay?: number, + + /** + * @cfg {String} [showType="mouseover"] + * Determines the type of event that triggers a tooltip + */ + showType?: string, + + /** + * @cfg {String} [hideType="mouseout"] + * Determines the type of event that hides a tooltip + */ + hideType?: string, + + /** + * @cfg {String} [title=""] + * Sets the content of a tooltip (referring to the title properties in markup) + */ + title?: string, + + }): this; + + /** + * @method update + * Changes the content of a tooltip + * + * @param {String} text + */ + update(newTitle: string): void; +} + +export interface UITreeNode { + /** @property {Array} [data=null] Data of a specifiednode */ + data?: any[]; + + /** @property {HTMLElement} [element=null] LI element of a specified node */ + element?: any; + + /** @property {Integer} [index=null] Index of a specified node */ + index?: number; + + /** @property {Integer} [nodenum=null] Unique number of a specifiede node at the current depth */ + nodenum?: number; + + /** @property {ui.tree.node} [parent=null] Variable that refers to the parent of the current node */ + parent?: UITreeNode; + + /** @property {Array} [children=null] List of child nodes of a specified node */ + children?: UITreeNode[]; + + /** @property {Integer} [depth=0] Depth of a specified node */ + depth?: number; + + /** @property {String} [type='open'] State value that indicates whether a child node is shown or hidden */ + type?: string; +} + +export interface UITreeBase { + appendNode(...args: any[]): UITreeNode; + insertNode(index: string, data: any): UITreeNode; + updateNode(index: string, data: any): UITreeNode; + removeNode(index: string): void; + removeNodes(): void; + openNode(index: string): void; + foldNode(index: string): void; + openNodeAll(index: string): void; + foldNodeAll(index: string): void; + + moveNode(index: string, targetIndex: number): void; + + getNode(index: string): UITreeNode; + + getNodeAll(index: string): UITreeNode[]; + + getNodeParent(index: string): UITreeNode; + + getRoot(): UITreeNode; +} + +export interface UITree { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {NodeObject} [root=null] + * Adds a root node (required). + */ + root?: UITreeNode, + + /** + * @cfg {Boolean} [rootHide=false] + * Hides a root node. + */ + rootHide?: boolean, + + /** + * @cfg {Boolean} [rootFold=false] + * Folds up a root node. + */ + rootFold?: boolean, + + /** + * @cfg {Boolean} [drag=false] + * It is possible to drag the movement of a node. + */ + drag?: boolean, + + /** + * @cfg {Boolean} [dragChild=true] + * It is possible to drag the node movement but the node is not changed to a child node of the target node. + */ + dragChild?: boolean + }): this; + + /** + * @method update + * Changes to the node at a specified index. + * + * @param {String} index + * @param {Array} data + */ + update(index: string, data: any[]): void; + + /** + * @method append + * Adds to a child node at a specified index. + * + * @param {Array/String} param1 index or data + * @param {Array} param2 null or data + */ + append(...args: any[]): void; + + /** + * @method insert + * Adds a node at a specified index. + * + * @param {String} index + * @param {Array} data + */ + insert(index: string, data: any[]): void; + + /** + * @method select + * Adds a node at a specified index. + * + * @param {String} index + * @return {NodeObject} node + */ + select(index: string): UITreeNode; + + /** + * @method unselect + * Removes the 'active' class from a selected node and gets an instance of the specified node. + */ + unselect(): void; + + /** + * @method remove + * Deletes a node at a specified index. + * + * @param {String} index + */ + remove(index: string): void; + /** + * @method reset + * Deletes all child nodes except for a root. + */ + reset(): void; + + /** + * @method move + * Moves a node at a specified index to the target index. + * + * @param {String} index + * @param {String} targetIndex + */ + move(index: string, targetIndex: string): void; + /** + * @method open + * Shows a child node at a specified index. + * + * @param {String} index + */ + open(index: string, e: any): void; + + /** + * @method fold + * Folds up a child node at a specified index. + * + * @param {String} index + */ + fold(index: string, e: any): void; + /** + * @method openAll + * Shows all child nodes at a specified index. + * + * @param {String} index + */ + openAll(index: string): void; + + /** + * @method foldAll + * Folds up all child nodes at a specified index. + * + * @param {String} index + */ + foldAll(index: string): void; + + /** + * @method list + * Return all nodes of the root. + * + * @return {Array} nodes + */ + list(): UITreeNode[]; + + /** + * @method listAll + * Returns all child nodes. + * + * @return {Array} nodes + */ + listAll(): UITreeNode[]; + + /** + * @method listParent + * Returns all parent nodes at a specified index. + * + * @param {String} index + * @return {Array} nodes + */ + listParents(index: string): UITreeNode[]; + + /** + * @method get + * Gets a node at a specified index + * + * @param {String} index + * @return {NodeObject} node + */ + get(index: string): UITreeNode; + + /** + * @method getAll + * Gets all nodes at a specified index including child nodes. + * + * @param {String} index + * @return {Array} nodes + */ + getAll(index: string): UITreeNode[]; + + /** + * @method activeIndex + * Gets the index of a node that is activated in an active state. + * + * @return {Integer} index + */ + activeIndex(): number; +} + +export interface UIWindow { + (selector: any, options?: { + tpl?: any, + event?: any, + /** + * @cfg {Integer} [width=400] + * Determines the horizontal size of a window + */ + width?: number, + + /** + * @cfg {Integer} [height=300] + * Determines the height of a window + */ + height?: number, + + /** + * @cfg {String/Integer} [left="auto"] + * Determines the X coordinate of a window + */ + left?: string|number, + + /** + * @cfg {String/Integer} [top="auto"] + * Determines the Y coordinate of a window + */ + top?: string|number, + + /** + * @cfg {String/Integer} [right="auto"] + * Determines the X coordinate based on the right side of a window + */ + right?: string|number, + + /** + * @cfg {String/Integer} [bottom="auto"] + * Determines the Y coordinate based on the bottom side of a window + */ + bottom?: string|number, + + /** + * @cfg {Boolean} [modal=false] + * Applies a modal UI to a window + */ + modal?: boolean, + + /** + * @cfg {Boolean} [move=true] + * It is possible to move a window + */ + move?: boolean, + + /** + * @cfg {Boolean} [resize=true] + * It is possible to resize a window + */ + resize?: boolean, + + /** + * @cfg {Integer} [modalIndex=0] + * Determines the z-index property of a modal UI + */ + modalIndex?: number + }): this; + + /** + * @method hide + * Hides a window + */ + hide(): void; + + /** + * @method show + * Shows a window at specified coordinates + * + * @param {Integer} x + * @param {Integer} y + */ + show(x: number, y: number): void; + + /** + * @method move + * Moves a window at specified coordinates + * + * @param {Integer} x + * @param {Integer} y + */ + move(x: number, y: number): void; + + /** + * @method update + * Changes the markup in the body area of a window + * + * @param {String} html + */ + update(html: string): void; + + /** + * @method setTitle + * Changes the markup of the title tag in the head area of a window + * + * @param {String} title + */ + setTitle(html: string): void; + + /** + * @method setSize + * Changes the horizontal/vertical size of a window + * + * @param {Integer} width + * @param {Integer} height + */ + setSize(w: number, h: number): void; + + /** + * @method resize + * Designates a scroll area if there is a lot of content in the window body area + */ + resize(): void; + + /** + * @method resizeModal + * Re-adjust the location of a modal window + */ + resizeModal(): void; +} diff --git a/jui/jui-tests.ts b/jui/jui-tests.ts new file mode 100644 index 0000000000..5bee2fdc2e --- /dev/null +++ b/jui/jui-tests.ts @@ -0,0 +1,124 @@ +/// + +import {jui} from 'jui-core'; +import { + UIAccordion, UIAutoComplete, UIColorPicker, UICombo, UIDatePicker, UIDropdown, UIModal, UINotify, + UIPaging, UIProgress, UIProperty, UISelect +} from 'jui'; + +jui.ready([ + 'ui.accordion', + 'ui.autocomplete', + 'ui.colorpicker', + 'ui.combo', + 'ui.datepicker', + 'ui.dropdown', + 'ui.modal', + 'ui.notify', + 'ui.paging', + 'ui.progress', + 'ui.property', + 'ui.select' +], function ( + accordion: UIAccordion, + autocomplete: UIAutoComplete, + colorpicker: UIColorPicker, + combo: UICombo, + datepicker: UIDatePicker, + dropdown: UIDropdown, + modal: UIModal, + notify: UINotify, + paging: UIPaging, + progress: UIProgress, + property: UIProperty, + select: UISelect +) { + let a: UIAccordion = accordion("#test", { + multipanel: false + }); + + console.log(a.activeIndex()); + + let autoComplete: UIAutoComplete = autocomplete("#test", { + words : [] + }); + + autoComplete.update([]); + + let colorPicker: UIColorPicker = colorpicker("#test", { + color: '#FFFF00' + }); + + console.log(colorPicker.getColor('hex')); + + let comboInstance: UICombo = combo("#test", { + keydown: true + }) + + console.log(comboInstance.getValue()); + + let datePicker: UIDatePicker = datepicker("#test", { + type: "daily" + }); + + datePicker.select(Date.now()); + + datePicker.select(2016, 1, 2); + + datePicker.select(new Date()); + + let dropdownInstance: UIDropdown = dropdown("#test", { + width: 100 + }) + + dropdownInstance.update([]); + + dropdownInstance.hide(); + + dropdownInstance.reload(); + + let m : UIModal = modal("#test", {autoHide: true}); + + m.show(); + + let n: UINotify = notify("#test"); + + n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'warning' }, 1000); + n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'success' }, 1000); + n.reset(); + + let p: UIPaging = paging("#test", { count :100, pageCount : 5 }); + + p.first(); + p.last(); + p.next(); + p.prev(); + p.page(10); + + let prog: UIProgress = progress("#test", { striped: true }); + + console.log(prog.getValue()); + + prog.setValue(100); + + let propertyView: UIProperty = property("#test", { + items : [ + { type : 'group', title : 'Sample Category'}, + { type : 'text', title : 'Category Name', key: 'sample-category-name', value : 'test'} + ] + }) + + console.log(propertyView.getValue()); + + let selectInstance: UISelect = select("#test", { + items : [ + { type : 'item', value : '0', text : 'first', html : '
test
', selected : true }, + { type : 'divider' } + ], + multi: true, + placeholder: 'Sample Select' + }); + + console.log(selectInstance.getValue()); + +}); diff --git a/jui/tsconfig.json b/jui/tsconfig.json new file mode 100644 index 0000000000..eb0b75ceb8 --- /dev/null +++ b/jui/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jui-tests.ts" + ] +} diff --git a/jui/tslint.json b/jui/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jui/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 9dad6b2b06440e2dbe7a498931e7f5e70f858c2b Mon Sep 17 00:00:00 2001 From: Tingan Ho Date: Wed, 18 Jan 2017 04:38:46 +0100 Subject: [PATCH 44/72] Grunt this typings (#13493) * Fixes semicolon * Fixes ordering * Fixes this typings * Fixes tests * Revert to IMultiTask --- grunt/grunt-tests.ts | 5 +- grunt/index.d.ts | 406 +++++++++++++++++++++---------------------- 2 files changed, 206 insertions(+), 205 deletions(-) diff --git a/grunt/grunt-tests.ts b/grunt/grunt-tests.ts index 980cbd6997..5dd6550582 100644 --- a/grunt/grunt-tests.ts +++ b/grunt/grunt-tests.ts @@ -9,6 +9,7 @@ interface MyTaskData { interface MyOptions { sourceRoot: string; + repeat: number; } // exports should work same as module.exports @@ -35,8 +36,8 @@ exports = (grunt: IGrunt) => { grunt.registerTask('default', ['uglify']); grunt.registerMultiTask('mytask', "short description", function() { - var currenttask: grunt.task.IMultiTask = this; - var options = currenttask.options({ + var currenttask = this; + var options = currenttask.options({ sourceRoot: "default" }); var valid = false; diff --git a/grunt/index.d.ts b/grunt/index.d.ts index 03ee4c48aa..4c8198dee9 100644 --- a/grunt/index.d.ts +++ b/grunt/index.d.ts @@ -25,11 +25,11 @@ declare namespace node { * {@link http://npmjs.org/doc/json.html} */ interface NodePackage { - name: string - version: string - description?: string - keywords?: string[] - homepage?: string + name: string; + version: string; + description?: string; + keywords?: string[]; + homepage?: string; } } @@ -53,61 +53,61 @@ declare namespace minimatch { /** * Dump a ton of stuff to stderr. */ - debug?: boolean + debug?: boolean; /** * Do not expand {a,b} and {1..3} brace sets. */ - nobrace?: boolean + nobrace?: boolean; /** * Disable ** matching against multiple folder names. */ - noglobstar?: boolean + noglobstar?: boolean; /** * Allow patterns to match filenames starting with a period, * even if the pattern does not explicitly have a period in that spot. */ // Note that by default, a/**\/b will not match a/.d/b, unless dot is set. - dot?: boolean + dot?: boolean; /** * Disable "extglob" style patterns like +(a|b). */ - noext?: boolean + noext?: boolean; /** * Perform a case-insensitive match. */ - nocase?: boolean + nocase?: boolean; /** * When a match is not found by minimatch.match, return a list containing the pattern itself. * When set, an empty list is returned if there are no matches. */ - nonull?: boolean + nonull?: boolean; /** * If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. * For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123. */ - matchBase?: boolean + matchBase?: boolean; /** * Suppress the behavior of treating # at the start of a pattern as a comment. */ - nocomment?: boolean + nocomment?: boolean; /** * Suppress the behavior of treating a leading ! character as negation. */ - nonegate?: boolean + nonegate?: boolean; /** * Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) */ - flipNegate?: boolean + flipNegate?: boolean; } } @@ -135,15 +135,15 @@ declare namespace grunt { * if two arguments are passed, grunt.config.set is called, * otherwise grunt.config.get is called. */ - (prop: string, value: any): any - (prop: string): any + (prop: string, value: any): any; + (prop: string): any; /** * Initialize a configuration object for the current project. * The specified configObject is used by tasks and can be accessed using the grunt.config method. * Nearly every project's Gruntfile will call this method. */ - init(config: IProjectConfig): void + init(config: IProjectConfig): void; /** * Get a value from the project's Grunt configuration. @@ -153,8 +153,8 @@ declare namespace grunt { * * @note Although this accepts a generic type, you may still get the wrong typed value. */ - get(prop: string): T - get(): ConfigModule + get(prop: string): T; + get(): ConfigModule; /** * Process a value, recursively expanding <% %> templates (via the grunt.template.process method) @@ -166,32 +166,32 @@ declare namespace grunt { * it will be expanded to the actual value. That, combined with grunt's task system automatically * flattening arrays, can be extremely useful. */ - process(value: string): T + process(value: string): T; /** * Get a raw value from the project's Grunt configuration, without processing <% %> template strings. * If prop is specified, that property's value is returned, or null if that property is not defined. * If prop isn't specified, a copy of the entire config object is returned. */ - getRaw(prop: string): T + getRaw(prop: string): T; /** * Set a value into the project's Grunt configuration. * @note any specified <% %> template strings will only be processed when config data is retrieved. */ - set(prop: string, value: T): T + set(prop: string, value: T): T; /** * Escape '.' dots in the given propString. This should be used for property names that contain dots. */ - escape(propString: string): string + escape(propString: string): string; /** * Fail the current task if one or more required config properties is missing, null or undefined. * One or more string or array config properties may be specified. */ - requires(prop: string, ...andProps: string[]): void - requires(prop: string[], ...andProps: string[][]): void + requires(prop: string, ...andProps: string[]): void; + requires(prop: string[], ...andProps: string[][]): void; /** * Recursively merges properties of the specified configObject into the current project configuration. @@ -210,42 +210,42 @@ declare namespace grunt { /** * Adds a listener to the end of the listeners array for the specified event. */ - addListener(event: string, listener: Function): EventModule - on(event: string, listener: Function): EventModule + addListener(event: string, listener: Function): EventModule; + on(event: string, listener: Function): EventModule; /** * Adds a listener that will be fired when any event is emitted. */ - onAny(listener: Function): EventModule + onAny(listener: Function): EventModule; /** * Removes the listener that will be fired when any event is emitted. */ - offAny(listener: Function): EventModule + offAny(listener: Function): EventModule; /** * Adds a one time listener for the event. * The listener is invoked only the first time the event is fired, after which it is removed. */ - once(event: string, listener: Function): EventModule + once(event: string, listener: Function): EventModule; /** * Adds a listener that will execute n times for the event before being removed. * The listener is invoked only the first time the event is fired, after which it is removed. */ - many(event: string, timesToListen: number, listener: Function): EventModule + many(event: string, timesToListen: number, listener: Function): EventModule; /** * Remove a listener from the listener array for the specified event. * Caution: changes array indices in the listener array behind the listener. */ - removeListener(event: string, listener: Function): EventModule - off(event: string, listener: Function): EventModule + removeListener(event: string, listener: Function): EventModule; + off(event: string, listener: Function): EventModule; /** * Removes all listeners, or those of the specified event. */ - removeAllListeners(event: string): EventModule + removeAllListeners(event: string): EventModule; /** * By default EventEmitters will print a warning if more than 10 listeners are added to it. @@ -254,25 +254,25 @@ declare namespace grunt { * * Set to zero for unlimited. */ - setMaxListener(n: number): void + setMaxListener(n: number): void; /** * Returns an array of listeners for the specified event. * This array can be manipulated, e.g. to remove listeners. */ - listeners(event: string): Function[] + listeners(event: string): Function[]; /** * Returns an array of listeners that are listening for any event that is specified. * This array can be manipulated, e.g. to remove listeners. */ - listenersAny(): Function[] + listenersAny(): Function[]; /** * Execute each of the listeners that may be listening for the specified event name * in order with the list of arguments. */ - emit(event: string, ...args: any[]): any + emit(event: string, ...args: any[]): any; } } @@ -294,14 +294,14 @@ declare namespace grunt { * Display a warning and abort Grunt immediately. * Grunt will continue processing tasks if the --force command-line option was specified. */ - warn(error: string, errorCode?: ErrorCode): void - warn(error: Error, errorCode?: ErrorCode): void + warn(error: string, errorCode?: ErrorCode): void; + warn(error: Error, errorCode?: ErrorCode): void; /** * Display a warning and abort Grunt immediately. */ - fatal(error: string, errorCode?: ErrorCode): void - fatal(error: Error, errorCode?: ErrorCode): void + fatal(error: string, errorCode?: ErrorCode): void; + fatal(error: Error, errorCode?: ErrorCode): void; } } @@ -311,7 +311,7 @@ declare namespace grunt { * {@link http://gruntjs.com/api/grunt.file#grunt.file.defaultencoding} */ interface IFileEncodedOption { - encoding: string + encoding: string; } /** @@ -329,7 +329,7 @@ declare namespace grunt { */ // noProcess?: string[] // noProcess?: boolean - noProcess?: any + noProcess?: any; } /** @@ -341,7 +341,7 @@ declare namespace grunt { * whose return value will be used as the destination file's contents. If * this function returns `false`, the file copy will be aborted. */ - process?: (buffer: Buffer) => boolean + process?: (buffer: Buffer) => boolean; } /** @@ -353,7 +353,7 @@ declare namespace grunt { * whose return value will be used as the destination file's contents. If * this function returns `false`, the file copy will be aborted. */ - process?: (file: string) => boolean + process?: (file: string) => boolean; } /** @@ -368,28 +368,28 @@ declare namespace grunt { * If you do have to change this value, it's recommended that you change * it as early as possible inside your Gruntfile. */ - defaultEncoding: string + defaultEncoding: string; /** * Read and return a file's contents. * Returns a string, unless options.encoding is null in which case it returns a Buffer. */ - read(filepath: string): string - read(filepath: string, options: IFileEncodedOption): Buffer + read(filepath: string): string; + read(filepath: string, options: IFileEncodedOption): Buffer; /** * Read a file's contents, parsing the data as JSON and returning the result. * @see FileModule.read for a list of supported options. */ - readJSON(filepath: string): any - readJSON(filepath: string, options: IFileEncodedOption): Buffer + readJSON(filepath: string): any; + readJSON(filepath: string, options: IFileEncodedOption): Buffer; /** * Read a file's contents, parsing the data as YAML and returning the result. * @see FileModule.read for a list of supported options. */ - readYAML(filepath: string): any - readYAML(filepath: string, options: IFileEncodedOption): Buffer + readYAML(filepath: string): any; + readYAML(filepath: string, options: IFileEncodedOption): Buffer; /** * Write the specified contents to a file, creating intermediate directories if necessary. @@ -398,28 +398,28 @@ declare namespace grunt { * @param contents If `contents` is a Buffer, encoding is ignored. * @param options If an encoding is not specified, default to grunt.file.defaultEncoding. */ - write(filepath: string, contents: string, options?: IFileEncodedOption): void - write(filepath: string, contents: Buffer): void + write(filepath: string, contents: string, options?: IFileEncodedOption): void; + write(filepath: string, contents: Buffer): void; /** * Copy a source file to a destination path, creating intermediate directories if necessary. */ - copy(srcpath: string, destpath: string): void - copy(srcpath: string, destpath: string, options: IFileWriteStringOption): void - copy(srcpath: string, destpath: string, options: IFileWriteBufferOption): void + copy(srcpath: string, destpath: string): void; + copy(srcpath: string, destpath: string, options: IFileWriteStringOption): void; + copy(srcpath: string, destpath: string, options: IFileWriteBufferOption): void; /** * Delete the specified filepath. Will delete files and folders recursively. * * @return true if the files could be deleted, otherwise false. */ - delete(filepath: string, options?: { force?: boolean }): boolean + delete(filepath: string, options?: { force?: boolean }): boolean; /** * Works like mkdir -p. Create a directory along with any intermediate directories. * If mode isn't specified, it defaults to 0777 & (~process.umask()). */ - mkdir(dirpath: string, mode?: string): void + mkdir(dirpath: string, mode?: string): void; /** * Recurse into a directory, executing callback for each file. @@ -434,7 +434,7 @@ declare namespace grunt { recurse( rootdir: string, callback: (abspath: string, rootdir: string, subdir: string, filename: string) => void - ): void + ): void; /** * Return a unique array of all file or directory paths that match the given globbing pattern(s). @@ -445,8 +445,8 @@ declare namespace grunt { * File paths are relative to the Gruntfile unless the current working directory is changed with * grunt.file.setBase or the --base command-line option. */ - expand(patterns: string[]): string[] - expand(options: IFilesConfig, patterns: string[]): string[] + expand(patterns: string[]): string[]; + expand(options: IFilesConfig, patterns: string[]): string[]; /** * Returns an array of src-dest file mapping objects. @@ -456,7 +456,7 @@ declare namespace grunt { * @see FileModule.expand method documentation for an explanation of how the patterns * and options arguments may be specified. */ - expandMapping(patterns: string[], dest: string, options: IExpandedFilesConfig): Array + expandMapping(patterns: string[], dest: string, options: IExpandedFilesConfig): Array; /** * Match one or more globbing patterns against one or more file paths. @@ -465,14 +465,14 @@ declare namespace grunt { * Paths matching patterns that begin with ! will be excluded from the returned array. * Patterns are processed in order, so inclusion and exclusion order is significant. */ - match(pattern: string, filepath: string): string[] - match(pattern: string, filepaths: string[]): string[] - match(patterns: string[], filepath: string): string[] - match(patterns: string[], filepaths: string[]): string[] - match(options: minimatch.IMinimatchOptions, pattern: string, filepath: string): string[] - match(options: minimatch.IMinimatchOptions, pattern: string, filepaths: string[]): string[] - match(options: minimatch.IMinimatchOptions, patterns: string[], filepath: string): string[] - match(options: minimatch.IMinimatchOptions, patterns: string[], filepaths: string[]): string[] + match(pattern: string, filepath: string): string[]; + match(pattern: string, filepaths: string[]): string[]; + match(patterns: string[], filepath: string): string[]; + match(patterns: string[], filepaths: string[]): string[]; + match(options: minimatch.IMinimatchOptions, pattern: string, filepath: string): string[]; + match(options: minimatch.IMinimatchOptions, pattern: string, filepaths: string[]): string[]; + match(options: minimatch.IMinimatchOptions, patterns: string[], filepath: string): string[]; + match(options: minimatch.IMinimatchOptions, patterns: string[], filepaths: string[]): string[]; /** * This method contains the same signature and logic as the grunt.file.match method, @@ -480,14 +480,14 @@ declare namespace grunt { * * @see FileModule.match */ - isMatch(pattern: string, filepath: string): boolean - isMatch(pattern: string, filepaths: string[]): boolean - isMatch(patterns: string[], filepath: string): boolean - isMatch(patterns: string[], filepaths: string[]): boolean - isMatch(options: minimatch.IMinimatchOptions, pattern: string, filepath: string): boolean - isMatch(options: minimatch.IMinimatchOptions, pattern: string, filepaths: string[]): boolean - isMatch(options: minimatch.IMinimatchOptions, patterns: string[], filepath: string): boolean - isMatch(options: minimatch.IMinimatchOptions, patterns: string[], filepaths: string[]): boolean + isMatch(pattern: string, filepath: string): boolean; + isMatch(pattern: string, filepaths: string[]): boolean; + isMatch(patterns: string[], filepath: string): boolean; + isMatch(patterns: string[], filepaths: string[]): boolean; + isMatch(options: minimatch.IMinimatchOptions, pattern: string, filepath: string): boolean; + isMatch(options: minimatch.IMinimatchOptions, pattern: string, filepaths: string[]): boolean; + isMatch(options: minimatch.IMinimatchOptions, patterns: string[], filepath: string): boolean; + isMatch(options: minimatch.IMinimatchOptions, patterns: string[], filepaths: string[]): boolean; /* @@ -498,55 +498,55 @@ declare namespace grunt { /** * Does the given path exist? */ - exists(path: string, ...append: string[]): boolean + exists(path: string, ...append: string[]): boolean; /** * Is the given path a symbolic link? */ - isLink(path: string, ...append: string[]): boolean + isLink(path: string, ...append: string[]): boolean; /** * Is the given path a symbolic link? */ - isDir(path: string, ...append: string[]): boolean + isDir(path: string, ...append: string[]): boolean; /** * Is the given path a file? */ - isFile(path: string, ...append: string[]): boolean + isFile(path: string, ...append: string[]): boolean; /** * Is a given file path absolute? */ - isPathAbsolute(path: string, ...append: string[]): boolean + isPathAbsolute(path: string, ...append: string[]): boolean; /** * Do all the specified paths refer to the same path? */ - arePathsEquivalent(path: string, ...append: string[]): boolean + arePathsEquivalent(path: string, ...append: string[]): boolean; /** * Are all descendant path(s) contained within the specified ancestor path? */ - doesPathContain(ancestorPath: string, decendantPaths: string[]): boolean + doesPathContain(ancestorPath: string, decendantPaths: string[]): boolean; /** * Is a given file path the current working directory (CWD)? */ - isPathCwd(path: string, ...append: string[]): boolean + isPathCwd(path: string, ...append: string[]): boolean; /** * Change grunt's current working directory (CWD). * By default, all file paths are relative to the Gruntfile. * This works just like the --base command-line option. */ - setBase(path: string, ...append: string[]): void + setBase(path: string, ...append: string[]): void; // External libraries // TODO: Create declarations - glob: any - minimatch: any - findup: any + glob: any; + minimatch: any; + findup: any; } /** @@ -564,18 +564,18 @@ declare namespace grunt { /** * Pattern(s) to match, relative to the {@link IExpandedFilesConfig.cwd}. */ - src?: string[] + src?: string[]; /** * Destination path prefix. */ - dest?: string + dest?: string; /** * Process a dynamic src-dest file mapping, * @see {@link http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically for more information. */ - expand?: boolean // = false + expand?: boolean; // = false /** * Either a valid fs.Stats method name: @@ -594,7 +594,7 @@ declare namespace grunt { */ // filter?: string // filter?: (src: string) => boolean - filter?: any + filter?: any; } /** @@ -605,22 +605,22 @@ declare namespace grunt { /** * Enables the following options */ - expand?: boolean // = true + expand?: boolean; // = true /** * All {@link IExpandedFilesConfig.src} matches are relative to (but don't include) this path. */ - cwd?: string + cwd?: string; /** * Replace any existing extension with this value in generated {@link IExpandedFilesConfig.dest} paths. */ - ext?: string + ext?: string; /** * Remove all path parts from generated {@link IExpandedFilesConfig.dest} paths. */ - flatten?: boolean + flatten?: boolean; /** * This function is called for each matched src file, (after extension renaming and flattening). @@ -628,7 +628,7 @@ declare namespace grunt { * and this function must return a new dest value. * If the same dest is returned more than once, each src which used it will be added to an array of sources for it. */ - rename?: Function + rename?: Function; } /** @@ -638,11 +638,11 @@ declare namespace grunt { /** * source filenames. */ - src: string[] + src: string[]; /** * destination filename. */ - dest: string + dest: string; } } @@ -658,48 +658,48 @@ declare namespace grunt { /** * Log the specified msg string, with no trailing newline. */ - write(msg: string): T + write(msg: string): T; /** * Log the specified msg string, with trailing newline. */ - writeln(msg: string): T + writeln(msg: string): T; /** * If msg string is omitted, logs ERROR in red, * otherwise logs >> msg, with trailing newline. */ - error(msg: string): T + error(msg: string): T; /** * Log an error with grunt.log.error, wrapping text to 80 columns using grunt.log.wraptext. */ - errorlns(msg: string): T + errorlns(msg: string): T; /** * If msg string is omitted, logs OK in green, otherwise logs >> msg, with trailing newline. */ - ok(msg: string): T + ok(msg: string): T; /** * Log an ok message with grunt.log.ok, wrapping text to 80 columns using grunt.log.wraptext. */ - oklns(msg: string): T + oklns(msg: string): T; /** * Log the specified msg string in bold, with trailing newline. */ - subhead(msg: string): T + subhead(msg: string): T; /** * Log a list of obj properties (good for debugging flags). */ - writeflags(obj: any): T + writeflags(obj: any): T; /** * Log an warning with grunt.log.warn */ - warn(msg: string): T + warn(msg: string): T; } /** @@ -707,7 +707,7 @@ declare namespace grunt { * but only log if the --verbose command-line option was specified. */ interface VerboseLogModule extends CommonLogging { - or: NotVerboseLogModule + or: NotVerboseLogModule; } /** @@ -715,15 +715,15 @@ declare namespace grunt { * but only log if the --verbose command-line option was not specified. */ interface NotVerboseLogModule extends CommonLogging { - or: VerboseLogModule + or: VerboseLogModule; } /** * {@link http://gruntjs.com/api/grunt.log} */ interface LogModule extends CommonLogging { - verbose: VerboseLogModule - notverbose: NotVerboseLogModule + verbose: VerboseLogModule; + notverbose: NotVerboseLogModule; } } @@ -742,20 +742,20 @@ declare namespace grunt { * var isDev = grunt.option('no-staging'); * assert(isDev === true) */ - (key: string, value: T): void - (key: string): T + (key: string, value: T): void; + (key: string): T; /** * Initialize grunt.option. * If initObject is omitted option will be initialized to an empty object * otherwise will be set to initObject. */ - init(initObject?: any): void + init(initObject?: any): void; /** * Returns the options as an array of command line parameters. */ - flags: grunt.IFlag[] + flags: grunt.IFlag[]; } } @@ -772,8 +772,8 @@ declare namespace grunt { * Whenever this "alias task" is run, every specified task in taskList will be run, in the order specified. * The taskList argument must be an array of tasks. */ - registerTask(taskName: string, taskList: string[]): void - registerTask(taskName: string, description: string, taskList: string[]): void + registerTask(taskName: string, taskList: string[]): void; + registerTask(taskName: string, description: string, taskList: string[]): void; /** * If a description and taskFunction are passed, the specified function will be executed @@ -785,8 +785,8 @@ declare namespace grunt { * * @note taskFunction.apply(scope: grunt.task.ITask, args: any[]) */ - registerTask(taskName: string, taskFunction: Function): void - registerTask(taskName: string, description: string, taskFunction: Function): void + registerTask(taskName: string, taskFunction: (this: ITask, ...args: any[]) => void): void; + registerTask(taskName: string, description: string, taskFunction: (this: ITask, ...args: any[]) => void): void; /** * Register a "multi task." A multi task is a task that implicitly iterates over all of its @@ -796,8 +796,8 @@ declare namespace grunt { * * @note taskFunction.apply(scope: grunt.task.IMultiTask, args: any[]) */ - registerMultiTask(taskName: string, taskFunction: Function): void - registerMultiTask(taskName: string, taskDescription: string, taskFunction: Function): void + registerMultiTask(taskName: string, taskFunction: (this: IMultiTask, ...args: any[]) => void): void; + registerMultiTask(taskName: string, taskDescription: string, taskFunction: (this: IMultiTask, ...args: any[]) => void): void; /** * Check with the name, if a task exists in the registered tasks. @@ -813,7 +813,7 @@ declare namespace grunt { * @param oldname The previous name of the task. * @param newname The new name for the task. */ - renameTask(oldname: string, newname: string): void + renameTask(oldname: string, newname: string): void; } /** @@ -825,25 +825,25 @@ declare namespace grunt { * Every specified task in taskList will be run immediately after the current task completes, * in the order specified. The task list can be an array of tasks or individual task arguments. */ - run(tasks: string[]): void - run(task: string, ...thenTasks: string[]): void + run(tasks: string[]): void; + run(task: string, ...thenTasks: string[]): void; /** * Empty the task queue completely. Unless additional tasks are enqueued, no more tasks will be run. */ - clearQueue(): void + clearQueue(): void; /** * Normalizes a task target configuration object into an array of src-dest file mappings. * This method is used internally by the multi task system this.files / grunt.task.current.files property. */ - normalizeMultiTaskFiles(data: grunt.config.IProjectConfig, targetname?: string): Array + normalizeMultiTaskFiles(data: grunt.config.IProjectConfig, targetname?: string): Array; /** * The currently running task or multitask. * @see http://gruntjs.com/api/inside-tasks */ - current: grunt.task.IMultiTask + current: grunt.task.IMultiTask; } interface AsyncResultCatcher { @@ -878,7 +878,7 @@ declare namespace grunt { * done(success); * }, 1000); */ - async(): AsyncResultCatcher + async(): AsyncResultCatcher; /** * If one task depends on the successful completion of another task (or tasks), @@ -898,41 +898,41 @@ declare namespace grunt { * One or more string or array config properties may be specified. * this.requiresConfig(prop [, prop [, ...]]) */ - requiresConfig(prop: string, ...andProps: string[]): void + requiresConfig(prop: string, ...andProps: string[]): void; /** * The name of the task, as defined in grunt.registerTask. * For example, if a "sample" task was run as grunt sample or grunt sample:foo, * inside the task function, this.name would be "sample". */ - name: string + name: string; /** * The name of the task, including any colon-separated arguments or flags specified on the command-line. * For example, if a "sample" task was run as grunt sample:foo, * inside the task function, this.nameArgs would be "sample:foo". */ - nameArgs: string + nameArgs: string; /** * An array of arguments passed to the task. * For example, if a "sample" task was run as grunt sample:foo:bar, * inside the task function, this.args would be ["foo", "bar"]. */ - args: string[] + args: string[]; /** * An object generated from the arguments passed to the task. * For example, if a "sample" task was run as grunt sample:foo:bar, * inside the task function, this.flags would be {foo: true, bar: true}. */ - flags: grunt.IFlag[] + flags: grunt.IFlag[]; /** * The number of grunt.log.error calls that occurred during this task. * This can be used to fail a task if errors were logged during the task. */ - errorCount: number + errorCount: number; /** * Returns an options object. @@ -940,8 +940,8 @@ declare namespace grunt { * object properties, which will be further overridden in multi tasks by any target-level * options object properties. */ - options(defaultsObj: any): ITaskOptions - options(defaultsObj: T): T + options(defaultsObj: T): T; + options(defaultsObj: any): ITaskOptions; } /** @@ -953,7 +953,7 @@ declare namespace grunt { * For example, if a "sample" multi task was run as grunt sample:foo with the config data * {sample: {foo: "bar"}}, inside the task function, this.target would be "foo". */ - target: string + target: string; /** * In a multi task, all files specified using any Grunt-supported file formats and options, @@ -973,14 +973,14 @@ declare namespace grunt { * @note it's possible that nonexistent files might be included in src values, * so you may want to explicitly test that source files exist before using them. */ - files: grunt.file.IFilesArray + files: grunt.file.IFilesArray; /** * In a multi task, all src files files specified via any file format are reduced to a single array. * If your task is "read only" and doesn't care about destination filepaths, * use this array instead of this.files. */ - filesSrc: string[] + filesSrc: string[]; /** * In a multi task, this is the actual data stored in the Grunt config object for the given target. @@ -990,7 +990,7 @@ declare namespace grunt { * @note It is recommended that this.options this.files and this.filesSrc are used instead of this.data, * as their values are normalized. */ - data: T + data: T; } /** @@ -1001,11 +1001,11 @@ declare namespace grunt { */ interface ITaskOptions { - options?: any + options?: any; // files?: grunt.file.IFilesArray // files?: grunt.file.IFilesMap - files?: any + files?: any; } /** @@ -1032,8 +1032,8 @@ declare namespace grunt { * * @note if the data object already has a grunt property, the grunt API will not be accessible in templates. */ - process(template: string): (options: any) => string - process(template: string, options: any): string + process(template: string): (options: any) => string; + process(template: string, options: any): string; /** * Set the Lo-Dash template delimiters to a predefined set in case you grunt.util._.template @@ -1041,7 +1041,7 @@ declare namespace grunt { * * The config delimiters <% %> are included by default. */ - setDelimiters(name: string): void + setDelimiters(name: string): void; /** * Add a named set of Lo-Dash template delimiters. @@ -1049,7 +1049,7 @@ declare namespace grunt { * You probably won't need to use this method, because the built-in delimiters should be sufficient, * but you could always add {% %} or [% %] style delimiters. */ - addDelimiters(name: string, opener: string, closer: string): void + addDelimiters(name: string, opener: string, closer: string): void; /** * Format a date using the dateformat library. @@ -1057,9 +1057,9 @@ declare namespace grunt { * * @note if you don't include the mask argument, dateFormat.masks.default is used */ - date(date?: Date, format?: string): string - date(date?: number, format?: string): string - date(date?: string, format?: string): string + date(date?: Date, format?: string): string; + date(date?: number, format?: string): string; + date(date?: string, format?: string): string; /** * Format today's date using the dateformat library using the current date and time. @@ -1067,7 +1067,7 @@ declare namespace grunt { * * @note if you don't include the mask argument, dateFormat.masks.default is used */ - today(format?: string): string + today(format?: string): string; } } @@ -1083,7 +1083,7 @@ declare namespace grunt { * Possible results are "number", "string", "boolean", "function", "regexp", "array", "date", * "error", "null", "undefined" and the catch-all "object". */ - kindOf(value: any): string + kindOf(value: any): string; /** * Return a new Error instance (that can be thrown) with the appropriate message. @@ -1091,38 +1091,38 @@ declare namespace grunt { * Also, if an Error object is specified for origError and Grunt was run with the --debug 9 option, * the original Error stack will be dumped. */ - error(message: string, origError?: Error): Error - error(error: Error, origError?: Error): Error - error(error: any, origError?: Error): Error + error(message: string, origError?: Error): Error; + error(error: Error, origError?: Error): Error; + error(error: any, origError?: Error): Error; /** * The linefeed character, normalized for the current operating system. * (\r\n on Windows, \n otherwise) */ - linefeed: string + linefeed: string; /** * Given a string, return a new string with all the linefeeds normalized for the current operating system. * (\r\n on Windows, \n otherwise) */ - normalizelf(str: string): string + normalizelf(str: string): string; /** * Recurse through nested objects and arrays, executing callbackFunction for each non-object value. * If continueFunction returns false, a given object or value will be skipped. */ - recurse(object: any, callbackFunction: (value: any) => void, continueFunction: (objOrValue: any) => boolean): void + recurse(object: any, callbackFunction: (value: any) => void, continueFunction: (objOrValue: any) => boolean): void; /** * Return string str repeated n times. */ - repeat(n: number, str: string): string + repeat(n: number, str: string): string; /** * Given str of "a/b", If n is 1, return "a" otherwise "b". * You can specify a custom separator if '/' doesn't work for you. */ - pluralize(n: number, str: string, separator?: string): string + pluralize(n: number, str: string, separator?: string): string; /** * Spawn a child process, keeping track of its stdout, stderr and exit code. @@ -1135,13 +1135,13 @@ declare namespace grunt { * result - The result object is an * code - The numeric exit code. */ - spawn(options: ISpawnOptions, done: (error: Error, result: ISpawnResult, code: number) => void): ISpawnedChild + spawn(options: ISpawnOptions, done: (error: Error, result: ISpawnResult, code: number) => void): ISpawnedChild; /** * Given an array or array-like object, return an array. * Great for converting arguments objects into arrays. */ - toArray(arrayLikeObject: any): T[] + toArray(arrayLikeObject: any): T[]; /** * Normalizes both "returns a value" and "passes result to a callback" functions to always @@ -1151,15 +1151,15 @@ declare namespace grunt { * it will continue to do so. */ callbackify(syncOrAsyncFunction: () => R): - (callback: (result: R) => void) => void + (callback: (result: R) => void) => void; callbackify(syncOrAsyncFunction: (a: A) => R): - (a: A, callback: (result: R) => void) => void + (a: A, callback: (result: R) => void) => void; callbackify(syncOrAsyncFunction: (a: A, b: B) => R): - (a: A, b: B, callback: (result: R) => void) => void + (a: A, b: B, callback: (result: R) => void) => void; callbackify(syncOrAsyncFunction: (a: A, b: B, c: C) => R): - (a: A, b: B, c: C, callback: (result: R) => void) => void + (a: A, b: B, c: C, callback: (result: R) => void) => void; callbackify(syncOrAsyncFunction: (a: A, b: B, c: C, d: D) => R): - (a: A, b: B, c: C, d: D, callback: (result: R) => void) => void + (a: A, b: B, c: C, d: D, callback: (result: R) => void) => void; // Internal libraries namespace: any @@ -1174,36 +1174,36 @@ declare namespace grunt { /** * The command to execute. It should be in the system path. */ - cmd?: string + cmd?: string; /** * If specified, the same grunt bin that is currently running will be * spawned as the child command, instead of the "cmd" option. * Defaults to false. */ - grunt?: boolean + grunt?: boolean; /** * An array of arguments to pass to the command. */ - args?: string[] + args?: string[]; /** * Additional options for the Node.js child_process spawn method. */ opts?: { - cwd?: string - stdio?: any - custom?: any - env?: any - detached?: boolean + cwd?: string; + stdio?: any; + custom?: any; + env?: any; + detached?: boolean; } /** * If this value is set and an error occurs, it will be used as the value * and null will be passed as the error value. */ - fallback?: any + fallback?: any; } /** @@ -1213,9 +1213,9 @@ declare namespace grunt { * not specified. */ interface ISpawnResult { - stdout: string - stderr: string - code: number + stdout: string; + stderr: string; + code: number; } /** @@ -1225,24 +1225,24 @@ declare namespace grunt { /** * Start the cmd with the options provided. */ - start(): void + start(): void; /** * Convenience function. Overrides options. restarts to 0. * Runs command exactly once no matter the options passed into the constructor. */ - once(): void + once(): void; /** * Convenience function. Overrides options.restarts to -1. * Runs command indefinitely no matter the options passed into the constructor. */ - forever(): void + forever(): void; /** * Shut down the child and don't let it restart. */ - kill(): void + kill(): void; } } @@ -1251,7 +1251,7 @@ declare namespace grunt { */ interface IFlag { - [flag: string]: boolean + [flag: string]: boolean; } /* @@ -1263,7 +1263,7 @@ declare namespace grunt { * An alias * @see grunt.config.ConfigModule.init */ - initConfig(config: grunt.config.IProjectConfig): void + initConfig(config: grunt.config.IProjectConfig): void; } interface ITaskComponents extends grunt.task.CommonTaskModule { @@ -1272,14 +1272,14 @@ declare namespace grunt { * This method can be used to load task-related files from a local Grunt plugin by * specifying the path to that plugin's "tasks" subdirectory. */ - loadTasks(tasksPath: string): void + loadTasks(tasksPath: string): void; /** * Load tasks from the specified Grunt plugin. * This plugin must be installed locally via npm, and must be relative to the Gruntfile. * Grunt plugins can be created by using the grunt-init gruntplugin template: grunt init:gruntplugin. */ - loadNpmTasks(pluginName: string): void + loadNpmTasks(pluginName: string): void; } } @@ -1293,28 +1293,28 @@ declare namespace grunt { */ interface IGrunt extends grunt.IConfigComponents, grunt.fail.FailModule, grunt.ITaskComponents { - config: grunt.config.ConfigModule + config: grunt.config.ConfigModule; - event: grunt.event.EventModule + event: grunt.event.EventModule; - fail: grunt.fail.FailModule + fail: grunt.fail.FailModule; - file: grunt.file.FileModule + file: grunt.file.FileModule; - log: grunt.log.LogModule + log: grunt.log.LogModule; - option: grunt.option.OptionModule + option: grunt.option.OptionModule; - task: grunt.task.TaskModule + task: grunt.task.TaskModule; - template: grunt.template.TemplateModule + template: grunt.template.TemplateModule; - util: grunt.util.UtilModule + util: grunt.util.UtilModule; /** * The current Grunt package.json metadata, as an object. */ - package: node.NodePackage + package: node.NodePackage; /** * The current Grunt version, as a string. This is just a shortcut to the grunt.package.version property. From 58bf82b7373235bed430b481571957a01122d166 Mon Sep 17 00:00:00 2001 From: Richard Harding Date: Wed, 18 Jan 2017 03:57:22 +0000 Subject: [PATCH 45/72] Added missing properties from TabProps (#13394) as per doc here https://react-bootstrap.github.io/components.html#tabs --- react-bootstrap/index.d.ts | 10 ++++++++++ react-bootstrap/react-bootstrap-tests.tsx | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index 7cfa207108..665c0cd1aa 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -602,7 +602,17 @@ declare namespace ReactBootstrap { // interface TabProps extends React.HTMLProps { animation?: boolean; + 'aria-labelledby'?:string; + bsClass?:string; eventKey?: any; // TODO: Add more specific type + onEnter?: Function; + onEntered?: Function; + onEntering?: Function; + onExit?: Function; + onExited?: Function; + onExiting?: Function; + unmountOnExit?: boolean; + tabClassName?:string; } interface TabClass extends React.ClassicComponentClass { Container: TabContainer; diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index e04a993be7..00bfae517c 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -598,6 +598,21 @@ export class ReactBootstrapTest extends Component { +
+ + {}} + onEntering={() => {}} + onExit={() => {}} + onExited={() => {}} + onExiting={()=>{}} + unmountOnExit={true} + bsClass="some style" tabClassName="classname" eventKey={1} title='Tab 1'>Tab 1 content + Tab 2 content + Tab 3 content + +
+
From 1bfcf017f422143f659302c38c97e910c26d69f0 Mon Sep 17 00:00:00 2001 From: Sebastiaan de Rooij Date: Wed, 18 Jan 2017 05:08:23 +0100 Subject: [PATCH 46/72] clamp-js definition files added (#13527) --- clamp-js/clamp-js-tests.ts | 28 ++++++++++++++++++++++++++++ clamp-js/index.d.ts | 25 +++++++++++++++++++++++++ clamp-js/tsconfig.json | 20 ++++++++++++++++++++ clamp-js/tslint.json | 1 + 4 files changed, 74 insertions(+) create mode 100755 clamp-js/clamp-js-tests.ts create mode 100755 clamp-js/index.d.ts create mode 100755 clamp-js/tsconfig.json create mode 100644 clamp-js/tslint.json diff --git a/clamp-js/clamp-js-tests.ts b/clamp-js/clamp-js-tests.ts new file mode 100755 index 0000000000..33accec319 --- /dev/null +++ b/clamp-js/clamp-js-tests.ts @@ -0,0 +1,28 @@ +import * as clamp from 'clamp-js'; + +const lineElement: HTMLElement = document.createElement('div'); +lineElement.style.setProperty('font-size', '3px'); +lineElement.style.setProperty('line-height', '5px'); +lineElement.style.setProperty('height', '11px'); +lineElement.style.setProperty('width', '15px'); + +const newtext: Text = document.createTextNode('Lorem ipsum, dolor sit amet.'); +lineElement.appendChild(newtext); + +const clampFromElement = clamp(lineElement); +const clampFromDefaults = clamp(lineElement, { + clamp: 'auto', + useNativeClamp: true, + splitOnChars: ['.', '-', '–', '—', ' '], + animate: false, + truncationChar: '…', + truncationHTML: null +}); +const clampWithOptions = clamp(lineElement, { + clamp: 1, + useNativeClamp: false, + splitOnChars: [','], + animate: true, + truncationChar: '--', + truncationHTML: '' +}); diff --git a/clamp-js/index.d.ts b/clamp-js/index.d.ts new file mode 100755 index 0000000000..2e86e544f7 --- /dev/null +++ b/clamp-js/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for clamp-js 0.7 +// Project: https://github.com/xavi160/Clamp.js +// Definitions by: Sebastiaan de Rooij +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace clamp { + export interface ClampOptions { + clamp?: number|string; + useNativeClamp?: boolean; + splitOnChars?: string[]; + animate?: boolean; + truncationChar?: string; + truncationHTML?: string | null; + } + + export interface ClampResponse { + 'original': string; + 'clamped': string; + } +} + +declare function clamp(element: HTMLElement, options?: clamp.ClampOptions): clamp.ClampResponse; + +export = clamp; +export as namespace clamp; diff --git a/clamp-js/tsconfig.json b/clamp-js/tsconfig.json new file mode 100755 index 0000000000..dc6338fcf2 --- /dev/null +++ b/clamp-js/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clamp-js-tests.ts" + ] +} diff --git a/clamp-js/tslint.json b/clamp-js/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/clamp-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From f1ff6bcaee3035e78eebdf88a76e621ba714bc9e Mon Sep 17 00:00:00 2001 From: Sebastian Himberger Date: Wed, 18 Jan 2017 06:47:27 +0100 Subject: [PATCH 47/72] Fix type signature of event handler (#13412) https://github.com/Hacker0x01/react-datepicker/edit/master/src/datepicker.jsx indicates these should be function types. --- react-datepicker/index.d.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index a158ba2f5f..aec8b61b72 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -16,7 +16,7 @@ declare module "react-datepicker" { disabled?: boolean; endDate?: {}; excludeDates?: any[]; - filterDate?():any; + filterDate?(): any; fixedHeight?: boolean; id?: string; includeDates?: any[]; @@ -25,10 +25,9 @@ declare module "react-datepicker" { maxDate?: {}; minDate?: {}; name?: string; - onBlur?():any; - onChange():any; - onChange(date?:any):any; - onFocus?():any; + onBlur?(handler: (e: any) => void): any; + onChange(handler: (date?: any, e?: any) => void): any; + onFocus?(handler: (e: any) => void): any; peekNextMonth?: boolean; placeholderText?: string; popoverAttachment?: string; @@ -40,7 +39,7 @@ declare module "react-datepicker" { scrollableYearDropdown?: boolean; selected?: {}; selectsEnd?: boolean; - selectsStart?: boolean; + selectsStart?: boolean; showMonthDropdown?: boolean; showYearDropdown?: boolean; showWeekNumbers?: boolean; From adec214d84e5328310f8b679995946f1a7c29e7d Mon Sep 17 00:00:00 2001 From: Mathias Kahl Date: Wed, 18 Jan 2017 06:47:49 +0100 Subject: [PATCH 48/72] Added parameters onProgress and onError to TextureLoader.load (#13523) * Augmented declarations of onProgress and onError Corrected signature of TextureLoader.load which was missing parameters onProgress and onLoad. Also specified the concrete interfaces ProgressEvent and ErrorEvent in declarations of load methods based on FileLoader. * updated three.js version in declaration header --- three/index.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/three/index.d.ts b/three/index.d.ts index e502b76115..3b0917f577 100644 --- a/three/index.d.ts +++ b/three/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for three.js 0.81 +// Type definitions for three.js 0.83 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -1998,7 +1998,7 @@ declare namespace THREE { responseType: string; withCredentials: string - load(url: string, onLoad?: (response: any) => void, onProgress?: (request: XMLHttpRequest) => void, onError?:(event: any) => void): any; + load(url: string, onLoad?: (responseText: string) => void, onProgress?: (request: ProgressEvent) => void, onError?:(event: ErrorEvent) => void): any; setMimeType(mimeType: MimeType): FileLoader; setPath(path: string) : FileLoader; setResponseType(responseType: string) : FileLoader; @@ -2010,7 +2010,7 @@ declare namespace THREE { manager: LoadingManager; - load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; parse(json: string): Font; } @@ -2030,7 +2030,7 @@ declare namespace THREE { * Begin loading from url * @param url */ - load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; + load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): HTMLImageElement; setCrossOrigin(crossOrigin: string): ImageLoader; setWithCredentials(value: string): ImageLoader; setPath(value: string): ImageLoader; @@ -2045,7 +2045,7 @@ declare namespace THREE { manager: LoadingManager; withCredentials: boolean; - load(url: string, onLoad?: (geometry: Geometry, materials: Material[]) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(url: string, onLoad?: (geometry: Geometry, materials: Material[]) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; setTexturePath( value: string ): void; parse(json: any, texturePath?: string): { geometry: Geometry; materials?: Material[] }; } @@ -2140,7 +2140,7 @@ declare namespace THREE { * * @param url */ - load(url: string, onLoad?: (texture: Texture) => void): Texture; + load(url: string, onLoad?: (texture: Texture) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Texture; setCrossOrigin(crossOrigin: string): TextureLoader; setWithCredentials(value: string): TextureLoader; setPath(path: string): TextureLoader; @@ -2153,7 +2153,7 @@ declare namespace THREE { corssOrigin: string; path: string; - load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; setCrossOrigin(crossOrigin: string): CubeTextureLoader; setPath(path: string): CubeTextureLoader; } @@ -2163,7 +2163,7 @@ declare namespace THREE { manager: LoadingManager; - load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; } export class DataTextureLoader extends BinaryTextureLoader {} @@ -2173,7 +2173,7 @@ declare namespace THREE { manager: LoadingManager; path: string; - load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; setPath(path: string): CompressedTextureLoader; } From f259e4f8547a7a402559c5788afd1a4221d57787 Mon Sep 17 00:00:00 2001 From: screendriver Date: Wed, 18 Jan 2017 06:50:53 +0100 Subject: [PATCH 49/72] Fixed Reference in http-link-header (#13844) --- http-link-header/http-link-header-tests.ts | 1 + http-link-header/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/http-link-header/http-link-header-tests.ts b/http-link-header/http-link-header-tests.ts index 85145dc8eb..5005f58071 100644 --- a/http-link-header/http-link-header-tests.ts +++ b/http-link-header/http-link-header-tests.ts @@ -21,6 +21,7 @@ isBool(has); const get = link.get('title', 'Example Website'); isReference(get); const rel = link.rel('alternate'); +rel['title'] !== 'bar'; isReference(rel); const set = link.set({ rel: 'next', uri: 'http://example.com/next' }); isReference(set); diff --git a/http-link-header/index.d.ts b/http-link-header/index.d.ts index ba208d8595..a8dca563d2 100644 --- a/http-link-header/index.d.ts +++ b/http-link-header/index.d.ts @@ -6,7 +6,7 @@ export interface Reference { uri: string; rel: string; - title?: string; + [index: string]: string; } export interface Link { refs: Reference[]; From 9cf9e12c1025367866353e18868e0c9d246a5630 Mon Sep 17 00:00:00 2001 From: Reuben Pasquini Date: Tue, 17 Jan 2017 23:52:34 -0600 Subject: [PATCH 50/72] webcomponents.js/ augment window.customeElements.register (#13842) the custome elements v1 standard introduces a new mechanism for registering custome elements: https://developers.google.com/web/fundamentals/getting-started/primers/customelements --- webcomponents.js/index.d.ts | 11 ++++++++++- webcomponents.js/webcomponents.js-tests.ts | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/webcomponents.js/index.d.ts b/webcomponents.js/index.d.ts index 6b658b6be9..c4e03d9c91 100644 --- a/webcomponents.js/index.d.ts +++ b/webcomponents.js/index.d.ts @@ -40,6 +40,13 @@ declare namespace webcomponents { flags: any; } + /** + * I just slapped this in here - sure it could be better ... :-) + */ + export interface CustomElements { + define( tagName:string, elementClass:any ):void; + } + } declare module "webcomponents.js" { @@ -59,4 +66,6 @@ interface Window { CustomElements: webcomponents.CustomElementsPolyfill; HTMLImports: webcomponents.HTMLImportsPolyfill; WebComponents: webcomponents.Polyfill; -} + + customElements: webcomponents.CustomElements; +} \ No newline at end of file diff --git a/webcomponents.js/webcomponents.js-tests.ts b/webcomponents.js/webcomponents.js-tests.ts index 28b1a42b5c..12738331a5 100644 --- a/webcomponents.js/webcomponents.js-tests.ts +++ b/webcomponents.js/webcomponents.js-tests.ts @@ -50,3 +50,17 @@ shadow.host; */ window.WebComponents.flags; +window.customElements.define( "lw-arrival-pie", + + /** + * ArrivalPie custom element + */ + class ArrivalPie extends HTMLElement { + // Can define constructor arguments if you wish. + constructor() { + // If you define a ctor, always call super() first! + // This is specific to CE and required by the spec. + super(); + } + } +); \ No newline at end of file From 08ebad8aade9002a3ea3075cd7f443862f45bf56 Mon Sep 17 00:00:00 2001 From: Ed Bishop Date: Wed, 18 Jan 2017 05:52:55 +0000 Subject: [PATCH 51/72] updated to add mobile typings. (#13395) * updated to add mobile typings. * update version number --- webdriverio/index.d.ts | 69 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 56 insertions(+), 13 deletions(-) diff --git a/webdriverio/index.d.ts b/webdriverio/index.d.ts index fbc6925fa9..1c1c5c1eb8 100644 --- a/webdriverio/index.d.ts +++ b/webdriverio/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for webdriverio 4.4.0 +// Type definitions for webdriverio 4.5.0 // Project: http://www.webdriver.io/ // Definitions by: Nick Malaguti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -243,18 +243,61 @@ declare namespace WebdriverIO { // Mobile export interface Client { - // flick - // flickDown - // flickLeft - // flickRight - // flickUp - // getGeoLocation - // getOrientation - // hold - // release - // setGeoLocation - // setOrientation - // touch + background(seconds: number): Client; + closeApp(): Client; + context(id?: string): Client; + contexts(): Client; + currentActivity(): any; + deviceKeyEvent(keyValue: number): Client; + getAppStrings(language: string): Client; + getCurrentDeviceActivity(): Client; + getDeviceTime(): Client; + getGeoLocation(): Client; + getNetworkConnection(): Client; + getOrientation(): Client; + hideDeviceKeyboard(strategy: 'tapOutside' | 'pressKey'): Client; + hold(selector: string): Client; + installApp(path: string): Client; + isAppInstalled(bundleId: string): Client; + isLocked(): boolean; + launch(): Client; + lock(seconds: number): Client; + longPressKeycode(keyCode: string, metaState: string): Client; + openNotifications(): Client; + orientation(setTo?: 'landscape' | 'portrait'): 'landscape' | 'portrait'; + performMultiAction(touchAttributes: any): Client; + performTouchAction(touchAttributes: any): Client; + pressKeycode(keyCode: string, metaState: string): Client; + pullFile(path: string): Client; + pullFolder(path: string): Client; + pushFile(path: string, data: any): Client; + release(selector: string): Client; + removeApp(bundleId: string): Client; + reset(): Client; + rotate(x: number, y: number, duration?: number, radius?: number, rotation?: number, touchCount?: number): Client; + setGeoLocation(location: { latitude: number, longitude: number, altitude: number }): Client; + setImmediateValue(id: string, value: string | Array): Client; + setNetworkConnection(flags: 0 | 1 | 2 | 4 | 6): Client; + setOrientation(setTo: 'landscape' | 'portrait'): Client; + settings(settings?: { [key: string]: string }): Client; + shake(): Client; + startActivity(appPackage: string, activity: string): Client; + strings(language: string): Client; + swipe(selector?: string, xOffset?: number, yOffset?: number, speed?: number): Client; + swipeDown(selector: string, speed?: number): Client; + swipeLeft(selector: string, speed?: number): Client; + swipeRight(selector: string, speed?: number): Client; + swipeUp(selector: string, speed?: number): Client; + toggleAirplaneMode(): Client; + toggleData(): Client; + toggleLocationServices(): Client; + toggleWiFi(): Client; + touch(selector: string, longClick: boolean): Client; + touchAction(selector: string, action: 'tap' | 'press'): Client; + touchId(validFingerprint?: boolean): Client; + touchMultiPerform(actions: any): Client; + touchPerform(actions: any): Client; + unlock(): Client; } export interface CssProperty { From fe9278d497cb2b8bf51cd3dbe09a24cc94726f44 Mon Sep 17 00:00:00 2001 From: Simon Date: Wed, 18 Jan 2017 14:56:22 +0900 Subject: [PATCH 52/72] [introjs] add hints interface to options (#14078) --- intro.js/index.d.ts | 14 +++++++++++++- intro.js/intro.js-tests.ts | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/intro.js/index.d.ts b/intro.js/index.d.ts index 7d417eb9a2..d7893018c2 100644 --- a/intro.js/index.d.ts +++ b/intro.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for intro.js 2.0 +// Type definitions for intro.js 2.4 // Project: https://github.com/usablica/intro.js // Definitions by: Maxime Fabre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,6 +10,12 @@ declare namespace IntroJs { position?: string; } + interface Hint { + hint: string; + element?: string|HTMLElement|Element; + hintPosition?: string; + } + interface Options { nextLabel?: string; prevLabel?: string; @@ -32,6 +38,7 @@ declare namespace IntroJs { hintPosition?: string; hintButtonLabel?: string; steps?: Step[]; + hints?: Hint[]; } interface IntroJs { @@ -56,6 +63,11 @@ declare namespace IntroJs { addHints(): IntroJs; + showHint(stepId: number): IntroJs; + showHints(): IntroJs; + hideHint(stepId: number): IntroJs; + hideHints(): IntroJs; + onhintsadded(callback: Function): IntroJs; onhintclick(callback: (hintElement: HTMLElement, item: Step, stepId: number) => any): IntroJs; onhintclose(callback: (stepId: number) => any): IntroJs; diff --git a/intro.js/intro.js-tests.ts b/intro.js/intro.js-tests.ts index f4356aa364..0d79c1bd21 100644 --- a/intro.js/intro.js-tests.ts +++ b/intro.js/intro.js-tests.ts @@ -35,6 +35,18 @@ intro.setOptions({ element: '#step5', intro : 'Get it, use it.' } + ], + hints: [ + { + element: '#step1', + hint: 'This is a hint', + hintPosition: 'middle-right' + }, + { + element: document.querySelectorAll('#step2')[0] as HTMLElement, + hint: 'This is another hint', + hintPosition: 'top-left' + } ] }); @@ -69,6 +81,10 @@ intro.start() alert('Hint close for Step ID ' + stepId); }) .addHints() + .showHint(1) + .showHints() + .hideHint(1) + .hideHints() .clone(); introWithElement.start() From fefb1124c3ed05e84878d555dcbcbf16d27f2ec4 Mon Sep 17 00:00:00 2001 From: AbraaoAlves Date: Wed, 18 Jan 2017 04:03:22 -0200 Subject: [PATCH 53/72] export IRouterHandler too (#13840) Export IRouterHandler like IRouterMatcher. I' like to use and extend it in global middlewares. --- express/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/express/index.d.ts b/express/index.d.ts index 7222c8d3d9..9b913db473 100644 --- a/express/index.d.ts +++ b/express/index.d.ts @@ -59,6 +59,7 @@ declare namespace e { interface Handler extends core.Handler { } interface IRoute extends core.IRoute { } interface IRouter extends core.IRouter { } + interface IRouterHandler extends core.IRouterHandler { } interface IRouterMatcher extends core.IRouterMatcher { } interface MediaType extends core.MediaType { } interface NextFunction extends core.NextFunction { } From 8a6e4ba426b34c0f19602825fce9a082a117939f Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Wed, 18 Jan 2017 08:06:46 +0200 Subject: [PATCH 54/72] [react-native] Fix NavigationBarRouteMapper (#13858) `NavigationBarRouteMapper` properties return type should be the same as the one of `Component.render()` method: `JSX.Element | null` --- react-native/index.d.ts | 6 +++--- react-native/tsconfig.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/react-native/index.d.ts b/react-native/index.d.ts index c9a9b76dc5..edf2822dd6 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -4390,9 +4390,9 @@ declare module "react" { export interface NavigationBarRouteMapper { - Title: (route: Route, nav: Navigator, index: number, navState: NavState) => React.ReactElement; - LeftButton: (route: Route, nav: Navigator, index: number, navState: NavState) => React.ReactElement; - RightButton: (route: Route, nav: Navigator, index: number, navState: NavState) => React.ReactElement; + Title: (route: Route, nav: Navigator, index: number, navState: NavState) => JSX.Element | null; + LeftButton: (route: Route, nav: Navigator, index: number, navState: NavState) => JSX.Element | null; + RightButton: (route: Route, nav: Navigator, index: number, navState: NavState) => JSX.Element | null; } /** diff --git a/react-native/tsconfig.json b/react-native/tsconfig.json index 930ac3d811..e4a4c95d57 100644 --- a/react-native/tsconfig.json +++ b/react-native/tsconfig.json @@ -19,4 +19,4 @@ "test/index.tsx", "test/animated.tsx" ] -} \ No newline at end of file +} From 63981f20b2bd7e9cd4ed5ca3ef2094930773acdc Mon Sep 17 00:00:00 2001 From: wmrowan Date: Tue, 17 Jan 2017 22:07:28 -0800 Subject: [PATCH 55/72] Ramda: add string signature to init and tail (#13884) --- ramda/index.d.ts | 6 ++++-- ramda/ramda-tests.ts | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/ramda/index.d.ts b/ramda/index.d.ts index 04623bdada..114ba38d6d 100644 --- a/ramda/index.d.ts +++ b/ramda/index.d.ts @@ -679,9 +679,10 @@ declare namespace R { indexOf(target: T): (list: T[]) => number; /** - * Returns all but the last element of a list. + * Returns all but the last element of a list or string. */ init(list: T[]): T[]; + init(list: string): string; /** * Inserts the supplied element into the list, at index index. Note that @@ -1467,9 +1468,10 @@ declare namespace R { T(): boolean; /** - * Returns all but the first element of a list. + * Returns all but the first element of a list or string. */ tail(list: T[]): T[]; + tail(list: string): string; /** * Returns a new list containing the first `n` elements of the given list. If diff --git a/ramda/ramda-tests.ts b/ramda/ramda-tests.ts index fc4e188362..e42ae16c63 100644 --- a/ramda/ramda-tests.ts +++ b/ramda/ramda-tests.ts @@ -575,6 +575,8 @@ interface Obj { a: number; b: number }; R.head(['fi', 'fo', 'fum']); //=> 'fi' R.head([10, 'ten']); // => 10 R.head(['10', 10]); // => '10' + R.head('abc'); //=> 'a' + R.head(''); //=> '' } (() => { @@ -591,6 +593,8 @@ interface Obj { a: number; b: number }; () => { R.init(['fi', 'fo', 'fum']); //=> ['fi', 'fo'] + R.init('abc'); //=> 'ab' + R.init(''); //=> '' } () => { @@ -623,6 +627,8 @@ interface Obj { a: number; b: number }; () => { R.last(['fi', 'fo', 'fum']); //=> 'fum' + R.last('abc'); //=> 'c' + R.last(''); //=> '' } () => { @@ -862,6 +868,8 @@ type Pair = KeyValuePair () => { R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] R.tail([1, 2, 3]); //=> [2, 3] + R.tail('abc'); //=> 'bc' + R.tail(''); //=> '' } () => { From e6689ec9d07318be60791de508966116e8f9e464 Mon Sep 17 00:00:00 2001 From: "Derek.Chia" Date: Wed, 18 Jan 2017 14:07:58 +0800 Subject: [PATCH 56/72] 1. Add pass more options throw navigatorOptions interface (#13889) 2. Add pass options throw createAlertDialog, createDialog and createPopover method. Which should be a typo because it exists in the comment but not in the method definition. --- onsenui/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/onsenui/index.d.ts b/onsenui/index.d.ts index 41b853250c..efe1be081a 100644 --- a/onsenui/index.d.ts +++ b/onsenui/index.d.ts @@ -464,6 +464,7 @@ interface ModalView { interface navigatorOptions { animation?: string; onTransitionEnd?: any; + [key: string]: any; //for options } /** @@ -806,7 +807,7 @@ interface onsStatic { * @return {Promise} Promise object that resolves to the alert dialog component object * @description Create a alert dialog instance from a template */ - createAlertDialog(page: string): any; + createAlertDialog(page: string, options?: any): any; /** * @param {String} page Page name. Can be either an HTML file or an containing a component * @param {Object} [options] Parameter object @@ -814,7 +815,7 @@ interface onsStatic { * @return {Promise} Promise object that resolves to the dialog component object * @description Create a dialog instance from a template */ - createDialog(page: string): any; + createDialog(page: string, options?: any): any; /** * @param {String} page Page name. Can be either an HTML file or an containing a component * @param {Object} [options] Parameter object @@ -822,7 +823,7 @@ interface onsStatic { * @return {Promise} Promise object that resolves to the popover component object * @description Create a popover instance from a template */ - createPopover(page: string): any; + createPopover(page: string, options?: any): any; /** * @description Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt From 6aa60e355a87aa02b7b0ad7d7dd337b5c4227b61 Mon Sep 17 00:00:00 2001 From: Luca Trazzi Date: Wed, 18 Jan 2017 07:08:57 +0100 Subject: [PATCH 57/72] ES6 export compatible (#13899) --- modernizr/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modernizr/index.d.ts b/modernizr/index.d.ts index 7c8a0233af..a447f3acea 100644 --- a/modernizr/index.d.ts +++ b/modernizr/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Boris Yankov , Theodore Brown , Leon Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = Modernizr; // support AMD require +export as namespace Modernizr; // keep a global namespace + declare namespace __Modernizr { interface AudioBoolean { ogg: boolean; From 8babe922646c59fc0e1eed4cd870282b8ba89caf Mon Sep 17 00:00:00 2001 From: z3ut Date: Wed, 18 Jan 2017 09:10:05 +0300 Subject: [PATCH 58/72] [leaflet-markercluster] Update for v1.0 (#13901) * Update for v1.0.2 * Changes for tslint and strictNullChecks * Make zoomToShowLayer() callback optional * Added MarkerCluster interface * refreshClusters() parameter types fix * Fixed initial broken indentation * Typo fix --- leaflet-markercluster/index.d.ts | 244 ++++++++++-------- .../leaflet-markercluster-tests.ts | 85 +++++- leaflet-markercluster/package.json | 2 +- leaflet-markercluster/tsconfig.json | 5 +- leaflet-markercluster/tslint.json | 3 + 5 files changed, 216 insertions(+), 123 deletions(-) create mode 100644 leaflet-markercluster/tslint.json diff --git a/leaflet-markercluster/index.d.ts b/leaflet-markercluster/index.d.ts index cc840985ae..ab8b6d9431 100644 --- a/leaflet-markercluster/index.d.ts +++ b/leaflet-markercluster/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.markercluster v0.4.0 +// Type definitions for Leaflet.markercluster 1.0 // Project: https://github.com/Leaflet/Leaflet.markercluster // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,137 +6,165 @@ /// declare namespace L { + export interface MarkerCluster extends L.Marker { + + /* + * Recursively retrieve all child markers of this cluster. + */ + getAllChildMarkers(): Marker[]; + + /* + * Returns the count of how many child markers we have. + */ + getChildCount(): number; + + /* + * Zoom to the minimum of showing all of the child markers, or the extents of this cluster. + */ + zoomToBounds(): void; + + /* + * Returns the cluster bounds. + */ + getBounds(): LatLngBounds; + } + export interface MarkerClusterGroupOptions { - /* - * When you mouse over a cluster it shows the bounds of its markers. - */ - showCoverageOnHover?: boolean; + /* + * When you mouse over a cluster it shows the bounds of its markers. + */ + showCoverageOnHover?: boolean; - /* - * When you click a cluster we zoom to its bounds. - */ - zoomToBoundsOnClick?: boolean; + /* + * When you click a cluster we zoom to its bounds. + */ + zoomToBoundsOnClick?: boolean; - /* - * When you click a cluster at the bottom zoom level we spiderfy it - * so you can see all of its markers. - */ - spiderfyOnMaxZoom?: boolean; + /* + * When you click a cluster at the bottom zoom level we spiderfy it + * so you can see all of its markers. + */ + spiderfyOnMaxZoom?: boolean; - /* - * Clusters and markers too far from the viewport are removed from the map - * for performance. - */ - removeOutsideVisibleBounds?: boolean; + /* + * Clusters and markers too far from the viewport are removed from the map + * for performance. + */ + removeOutsideVisibleBounds?: boolean; - /* - * Smoothly split / merge cluster children when zooming and spiderfying. - * If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible). - */ - animate?: boolean; + /* + * Smoothly split / merge cluster children when zooming and spiderfying. + * If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible). + */ + animate?: boolean; - /* - * If set to true (and animate option is also true) then adding individual markers to the - * MarkerClusterGroup after it has been added to the map will add the marker and animate it - * into the cluster. Defaults to false as this gives better performance when bulk adding markers. - * addLayers does not support this, only addLayer with individual Markers. - */ - animateAddingMarkers?: boolean; + /* + * If set to true (and animate option is also true) then adding individual markers to the + * MarkerClusterGroup after it has been added to the map will add the marker and animate it + * into the cluster. Defaults to false as this gives better performance when bulk adding markers. + * addLayers does not support this, only addLayer with individual Markers. + */ + animateAddingMarkers?: boolean; - /* - * If set, at this zoom level and below markers will not be clustered. This defaults to disabled. - */ - disableClusteringAtZoom?: number; + /* + * If set, at this zoom level and below markers will not be clustered. This defaults to disabled. + */ + disableClusteringAtZoom?: number; - /* - * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * 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 | ((zoom: number) => number); + /* + * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. + * 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 | ((zoom: number) => number); - /* - * Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. - * Defaults to empty - */ - polygonOptions?: PolylineOptions; + /* + * Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. + * Defaults to empty + */ + polygonOptions?: PolylineOptions; - /* - * If set to true, overrides the icon for all added markers to make them appear as a 1 size cluster. - */ - singleMarkerMode?: boolean; + /* + * If set to true, overrides the icon for all added markers to make them appear as a 1 size cluster. + */ + singleMarkerMode?: boolean; - /* - * Allows you to specify PolylineOptions to style spider legs. - * By default, they are { weight: 1.5, color: '#222', opacity: 0.5 }. - */ - spiderLegPolylineOptions?: PolylineOptions; + /* + * Allows you to specify PolylineOptions to style spider legs. + * By default, they are { weight: 1.5, color: '#222', opacity: 0.5 }. + */ + spiderLegPolylineOptions?: PolylineOptions; - /* - * Increase from 1 to increase the distance away from the center that spiderfied markers are placed. - * Use if you are using big marker icons (Default: 1). - */ - spiderfyDistanceMultiplier?: number; + /* + * Increase from 1 to increase the distance away from the center that spiderfied markers are placed. + * Use if you are using big marker icons (Default: 1). + */ + spiderfyDistanceMultiplier?: number; - /* - * Function used to create the cluster icon - */ - iconCreateFunction?: any; + /* + * Function used to create the cluster icon + */ + iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon); - /* - * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. - */ - chunkedLoading?: boolean; + /* + * 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; + /* + * Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms. + */ + chunkDelay?: number; } - export class MarkerClusterGroup extends FeatureGroup { - constructor(); - constructor(options: MarkerClusterGroupOptions); + export interface MarkerClusterGroup extends FeatureGroup { - /* - * Bulk methods for adding and removing markers and should be favoured over the - * single versions when doing bulk addition/removal of markers. - */ - addLayers(layers:ILayer[]):MarkerClusterGroup; - removeLayers(layers:ILayer[]):MarkerClusterGroup; + /* + * Bulk methods for adding and removing markers and should be favoured over the + * single versions when doing bulk addition/removal of markers. + */ + addLayers(layers: Layer[]): this; + removeLayers(layers: Layer[]): this; - clearLayers():MarkerClusterGroup; + clearLayers(): this; - /* - * If you have a marker in your MarkerClusterGroup and you want to get the visible - * parent of it - */ - getVisibleParent(marker: Marker): Marker; + /* + * If you have a marker in your MarkerClusterGroup and you want to get the visible + * parent of it + */ + getVisibleParent(marker: Marker): Marker; - /* - * If you have customized the clusters icon to use some data from the contained markers, - * and later that data changes, use this method to force a refresh of the cluster icons. - */ - refreshClusters():MarkerClusterGroup; - refreshClusters(layerGroup:LayerGroup):MarkerClusterGroup; - refreshClusters(marker: Marker):MarkerClusterGroup; - refreshClusters(markers: Marker[]):MarkerClusterGroup; + /* + * If you have customized the clusters icon to use some data from the contained markers, + * and later that data changes, use this method to force a refresh of the cluster icons. + */ + refreshClusters(clusters?: Marker | Marker[] | LayerGroup | {[index: string]: Layer}): this; - /* - * Returns the total number of markers contained within that cluster. - */ - getChildCount(): number; + /* + * Returns the total number of markers contained within that cluster. + */ + getChildCount(): number; - /* - * Returns the array of total markers contained within that cluster. - */ - getAllChildMarkers(): Marker[]; + /* + * 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; + /* + * Returns true if the given layer (marker) is in the cluster. + */ + hasLayer(layer: Layer): boolean; + + /* + * Zooms to show the given marker (spiderfying if required), + * calls the callback when the marker is visible on the map. + */ + zoomToShowLayer(layer: Layer, callback?: () => void): void; } + + /* + * Create a marker cluster group, optionally given marker cluster group options. + */ + export function markerClusterGroup(options?: MarkerClusterGroupOptions): MarkerClusterGroup; } diff --git a/leaflet-markercluster/leaflet-markercluster-tests.ts b/leaflet-markercluster/leaflet-markercluster-tests.ts index e579db5309..346239f836 100644 --- a/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/leaflet-markercluster/leaflet-markercluster-tests.ts @@ -1,19 +1,78 @@ -var map: L.Map; -var markerClusterGroup: L.MarkerClusterGroup; +const polylineOptions: L.PolylineOptions = {}; +const icon: L.Icon = L.icon({ iconUrl: 'foo' }); -// CircleMarker -var circleMarker: L.CircleMarker = new L.CircleMarker(new L.LatLng(0, 0)); +let markerClusterGroupOptions: L.MarkerClusterGroupOptions = {}; +markerClusterGroupOptions = { + showCoverageOnHover: true, + zoomToBoundsOnClick: false, + spiderfyOnMaxZoom: true, + removeOutsideVisibleBounds: false, + animate: true, + animateAddingMarkers: false, + disableClusteringAtZoom: 12, + maxClusterRadius: 40, + polygonOptions: polylineOptions, + singleMarkerMode: true, + spiderLegPolylineOptions: polylineOptions, + spiderfyDistanceMultiplier: 2, + iconCreateFunction: (cluster: L.MarkerCluster) => { + const childMarkers: L.Marker[] = cluster.getAllChildMarkers(); + const childCount: number = cluster.getChildCount(); + cluster.zoomToBounds(); + const bounds: L.LatLngBounds = cluster.getBounds(); + return icon; + }, + chunkedLoading: false, + chunkDelay: 100 +} -markerClusterGroup.addLayer(circleMarker); -map.addLayer(markerClusterGroup); -map.removeLayer(markerClusterGroup); +let markerClusterGroup: L.MarkerClusterGroup; +markerClusterGroup = L.markerClusterGroup(); +markerClusterGroup = L.markerClusterGroup(markerClusterGroupOptions); -// Marker -var marker = new L.Marker(new L.LatLng(0, 0)); +let map = L.map('foo'); -markerClusterGroup.addLayers([circleMarker, marker]); -map.addLayer(markerClusterGroup); -markerClusterGroup.refreshClusters(); -map.removeLayer(markerClusterGroup); +markerClusterGroup = markerClusterGroup.addTo(map); +map = map + .addLayer(markerClusterGroup) + .removeLayer(markerClusterGroup); + +const latLng: L.LatLng = L.latLng(10, 10); + +const layer: L.Layer = L.marker(latLng); +const layers: L.Layer[] = [layer]; + +let marker: L.Marker = L.marker(latLng); +let markers: L.Marker[] = [marker]; + +const layerGroup: L.LayerGroup = L.layerGroup(layers); + +marker = markerClusterGroup.getVisibleParent(marker); + +markerClusterGroup = markerClusterGroup + // Layers + .addLayer(layer) + .removeLayer(layer) + .addLayers(layers) + .removeLayers(layers) + .clearLayers() + // RefreshClusters + .refreshClusters() + .refreshClusters(layerGroup) + .refreshClusters(marker) + .refreshClusters(markers) + .refreshClusters(markerClusterGroup) + .refreshClusters({ id_any: layer }); + +const childCount: number = markerClusterGroup.getChildCount(); + +markers = markerClusterGroup.getAllChildMarkers(); + +markerClusterGroup.zoomToShowLayer(marker); +markerClusterGroup.zoomToShowLayer(marker, () => {}); + +let hasLayer: boolean; +hasLayer = markerClusterGroup.hasLayer(layer); +hasLayer = markerClusterGroup.hasLayer(marker); diff --git a/leaflet-markercluster/package.json b/leaflet-markercluster/package.json index 711ba15e43..b06daabe04 100644 --- a/leaflet-markercluster/package.json +++ b/leaflet-markercluster/package.json @@ -1,5 +1,5 @@ { "dependencies": { - "@types/leaflet": "^0.7" + "@types/leaflet": "^1.0" } } \ No newline at end of file diff --git a/leaflet-markercluster/tsconfig.json b/leaflet-markercluster/tsconfig.json index e07708e702..c2dd4d0233 100644 --- a/leaflet-markercluster/tsconfig.json +++ b/leaflet-markercluster/tsconfig.json @@ -4,8 +4,11 @@ "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", + "typeRoots": [ + "../" + ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/leaflet-markercluster/tslint.json b/leaflet-markercluster/tslint.json new file mode 100644 index 0000000000..192203ab54 --- /dev/null +++ b/leaflet-markercluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file From fe920a4c27f4da5b99c541a6d3c725967fb3839a Mon Sep 17 00:00:00 2001 From: Derek Brown Date: Wed, 18 Jan 2017 01:12:22 -0500 Subject: [PATCH 59/72] Update index.d.ts (#13912) Added new option value: "errorOnMissing" https://www.npmjs.com/package/node-cache --- node-cache/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node-cache/index.d.ts b/node-cache/index.d.ts index c9d82eb8cc..37b4389d69 100644 --- a/node-cache/index.d.ts +++ b/node-cache/index.d.ts @@ -122,6 +122,7 @@ declare namespace NodeCache { stdTTL?: number; checkperiod?: number; useClones?: boolean; + errorOnMissing?: boolean; } interface Stats { From 558a6ef46c20c429274c5fb59a675ff1d0179880 Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 18 Jan 2017 09:13:22 +0300 Subject: [PATCH 60/72] Actualized to fit version 2.0. (#13938) --- speakeasy/index.d.ts | 57 +++++++++++++++++++++++++++++++----- speakeasy/speakeasy-tests.ts | 18 +++++++++++- 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/speakeasy/index.d.ts b/speakeasy/index.d.ts index 6c2245ad59..15ec90c09a 100644 --- a/speakeasy/index.d.ts +++ b/speakeasy/index.d.ts @@ -1,11 +1,9 @@ -// Type definitions for speakeasy v1.0.4 +// Type definitions for speakeasy v2.0.0 // Project: https://github.com/markbao/speakeasy -// Definitions by: Lucas Woo +// Definitions by: Lucas Woo , Alexander Batukhtin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -interface IKey { +interface Key { ascii: string; base32: string; hex: string; @@ -13,6 +11,15 @@ interface IKey { qr_code_hex: string; qr_code_base32: string; google_auth_qr: string; + otpauth_url?: string; +} + +interface DigestOptions { + secret: string; + counter: string; + encoding?: string; + algorithm?: string; + key?: string; } interface GenerateOptions { @@ -23,13 +30,27 @@ interface GenerateOptions { name?: string; } +interface GenerateSecretOptions { + length?: number; + name?: string; + qr_codes?: boolean; + google_auth_qr?: boolean; + otpauth_url?: boolean; + symbols?: boolean; +} + interface TotpOptions { - key: string; + key?: string; step?: number; time?: number; initial_time?: number; length?: number; encoding?: string; + counter?: number; + epoch?: number; + secret?: string; + digest?: () => string; + algorithm?: string; } interface HotpOptions { @@ -37,9 +58,31 @@ interface HotpOptions { counter: number; length?: number; encoding?: string; + digits?: number; + digest?: () => string; } -export declare function generate_key(options: GenerateOptions): IKey; +interface OtpauthURLOptions { + secret: string; + label: string; + issuer?: any; + type?: string; + counter?: number; + algorithm?: string; + digits?: number; + period?: number; + encoding?: string; +} + +export declare function digest(options: DigestOptions): string; + +export declare function generate_key(options: GenerateOptions): Key; + +export declare function generateSecret(options: GenerateSecretOptions): Key; + +export declare function generateSecretASCII(length?: number, symbols?: boolean): string; + +export declare function otpauthURL(options: OtpauthURLOptions): string; export declare function hotp(options: HotpOptions): string; diff --git a/speakeasy/speakeasy-tests.ts b/speakeasy/speakeasy-tests.ts index 3c8da97140..ae1ed061da 100644 --- a/speakeasy/speakeasy-tests.ts +++ b/speakeasy/speakeasy-tests.ts @@ -1,4 +1,4 @@ -import speakeasy = require('speakeasy'); +import * as speakeasy from 'speakeasy'; speakeasy.generate_key({length: 20, google_auth_qr: true}); @@ -22,3 +22,19 @@ speakeasy.totp({key: 'secret', time: 159183717}); // use a initial time. speakeasy.totp({key: 'secret', initial_time: 4182881485}); + +speakeasy.generateSecret({ + length: 3, + name: 'testName', + qr_codes: true, + google_auth_qr: true, + otpauth_url: true, + symbols: true +}); + +speakeasy.generateSecretASCII(5, true); + +speakeasy.otpauthURL({ + secret: 'otpauthURLSecret', + label: 'otpauthURLLength' +}); \ No newline at end of file From 777b33e5fa0a06ab606b2f10e1a4a71c9ab9db3d Mon Sep 17 00:00:00 2001 From: Julien CROUZET Date: Wed, 18 Jan 2017 07:13:39 +0100 Subject: [PATCH 61/72] Restify : Router.find() method (#13941) --- restify/index.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/restify/index.d.ts b/restify/index.d.ts index 40a6938127..f53aa0eba9 100644 --- a/restify/index.d.ts +++ b/restify/index.d.ts @@ -380,6 +380,15 @@ interface Router { * @returns {String} the name of the deleted route (or false if it was not matched) */ unmount: (name: string) => string | boolean; + + /** + * finds the route for a given request and response. + * @param {Request} req the request object + * @param {Response} res the response object + * @param {Function} callback operation callback + * @returns {undefined} + */ + find: (req: Request, res: Response, callback: (err: Error, route: Route) => void) => void; } interface Server extends http.Server { From 2a904580274c112ec06336fe6a737991199dd1b2 Mon Sep 17 00:00:00 2001 From: Dmitry Jakubovsky Date: Wed, 18 Jan 2017 08:14:38 +0200 Subject: [PATCH 62/72] react-day-picker: Fired error with flag strictNullChecks=true (#13960) * With flag strictNullChecks=true fire error. Fix it. * Add typescript version * enable strictNullChecks * Fix errors in tests: add constraints. --- react-day-picker/index.d.ts | 7 ++++--- react-day-picker/react-day-picker-tests.tsx | 5 +++++ react-day-picker/tsconfig.json | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/react-day-picker/index.d.ts b/react-day-picker/index.d.ts index c3eb4a3170..f1a987cab3 100644 --- a/react-day-picker/index.d.ts +++ b/react-day-picker/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gpbl/react-day-picker // Definitions by: Giampaolo Bellavite , Jason Killian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.0 /// @@ -22,9 +23,9 @@ declare namespace ReactDayPicker { } interface DayModifiers { - selected?: boolean; - disabled?: boolean; - [name: string]: boolean; + selected?: boolean; + disabled?: boolean; + [name: string]: boolean | undefined; } interface Modifiers { diff --git a/react-day-picker/react-day-picker-tests.tsx b/react-day-picker/react-day-picker-tests.tsx index 33fbadf900..e8a17b5087 100644 --- a/react-day-picker/react-day-picker-tests.tsx +++ b/react-day-picker/react-day-picker-tests.tsx @@ -24,6 +24,11 @@ interface MyCaptionProps extends ReactDayPicker.CaptionElementProps { } class Caption extends React.Component { render() { const { date, locale, localeUtils, onClick } = this.props; + + if (!date || !localeUtils || typeof locale === 'undefined') { + return null + } + return (
{ localeUtils.formatMonthTitle(date, locale) } diff --git a/react-day-picker/tsconfig.json b/react-day-picker/tsconfig.json index a5b010b1a8..c0098d0174 100644 --- a/react-day-picker/tsconfig.json +++ b/react-day-picker/tsconfig.json @@ -4,7 +4,7 @@ "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "jsx": "react", "typeRoots": [ @@ -18,4 +18,4 @@ "index.d.ts", "react-day-picker-tests.tsx" ] -} \ No newline at end of file +} From c7f6012baed03512dd2e58e61ec89742f508ef91 Mon Sep 17 00:00:00 2001 From: Juan David Henao Zapata Date: Wed, 18 Jan 2017 01:14:55 -0500 Subject: [PATCH 63/72] Update mocha constructor params (#13962) Actually mocha constructor support this new objects --- mocha/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 9ac84fa097..41d08c685d 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -69,6 +69,8 @@ declare class Mocha { ui?: string; reporter?: string; timeout?: number; + reporterOptions?: any; + slow?: number; bail?: boolean; }); From 398df79910b5a13236ca241aee071d09f1491f6a Mon Sep 17 00:00:00 2001 From: IdeaHunter Date: Wed, 18 Jan 2017 09:21:17 +0300 Subject: [PATCH 64/72] [sharepoint] Add tslint.json, fix all lint errors, add version into header (#13971) --- sharepoint/index.d.ts | 1562 +++++++++++++++----------------- sharepoint/sharepoint-tests.ts | 819 ++++++++--------- sharepoint/tslint.json | 3 + 3 files changed, 1144 insertions(+), 1240 deletions(-) create mode 100644 sharepoint/tslint.json diff --git a/sharepoint/index.d.ts b/sharepoint/index.d.ts index 75e67656b8..22bed0c0aa 100644 --- a/sharepoint/index.d.ts +++ b/sharepoint/index.d.ts @@ -1,30 +1,30 @@ -// Type definitions for SharePoint 2010 and 2013 +// Type definitions for SharePoint: 2010.1 / 2013.1 // Project: https://github.com/gandjustas/sptypescript // Definitions by: Stanislav Vyshchepan , Andrey Markeev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare var _spBodyOnLoadFunctions: Function[]; +declare var _spBodyOnLoadFunctions: Array<() => void>; declare var _spBodyOnLoadFunctionNames: string[]; declare var _spBodyOnLoadCalled: boolean; declare function ExecuteOrDelayUntilBodyLoaded(initFunc: () => void): void; declare function ExecuteOrDelayUntilScriptLoaded(func: () => void, depScriptFileName: string): boolean; -declare function ExecuteOrDelayUntilEventNotified(func: Function, eventName: string): boolean; -declare var Strings:any; +declare function ExecuteOrDelayUntilEventNotified(func: (...args: any[]) => void, eventName: string): boolean; +declare var Strings: any; declare namespace SP { export class SOD { static execute(fileName: string, functionName: string, ...args: any[]): void; static executeFunc(fileName: string, typeName: string, fn: () => void): void; - static executeOrDelayUntilEventNotified(func: Function, eventName: string): boolean; + static executeOrDelayUntilEventNotified(func: (...args: any[]) => void, eventName: string): boolean; static executeOrDelayUntilScriptLoaded(func: () => void, depScriptFileName: string): boolean; static notifyScriptLoadedAndExecuteWaitingJobs(scriptFileName: string): void; static notifyEventAndExecuteWaitingJobs(eventName: string, args?: any[]): void; static registerSod(fileName: string, url: string): void; static registerSodDep(fileName: string, dependentFileName: string): void; static loadMultiple(keys: string[], fn: () => void, bSync?: boolean): void; - static delayUntilEventNotified(func: Function, eventName: string): void; + static delayUntilEventNotified(func: (...args: any[]) => void, eventName: string): void; static get_prefetch(): boolean; static set_prefetch(value: boolean): void; @@ -34,17 +34,17 @@ declare namespace SP { } export enum ListLevelPermissionMask { - viewListItems,//: 1, - insertListItems,//: 2, - editListItems,//: 4, - deleteListItems,//: 8, - approveItems,//: 16, - openItems,//: 32, - viewVersions,//: 64, - deleteVersions,//: 128, - breakCheckout,//: 256, - managePersonalViews,//: 512, - manageLists//: 2048 + viewListItems, //: 1, + insertListItems, //: 2, + editListItems, //: 4, + deleteListItems, //: 8, + approveItems, //: 16, + openItems, //: 32, + viewVersions, //: 64, + deleteVersions, //: 128, + breakCheckout, //: 256, + managePersonalViews, //: 512, + manageLists //: 2048 } export class HtmlBuilder { @@ -113,21 +113,21 @@ declare namespace SP { fromJson(json: { High: number; Low: number; }): void; } - export module ListOperation { - export module ViewOperation { + export namespace ListOperation { + export namespace ViewOperation { export function getSelectedView(): string; export function navigateUp(viewId: string): void; export function refreshView(viewId: string): void; } - export module Selection { + export namespace Selection { export function selectListItem(iid: string, bSelect: boolean): void; - export function getSelectedItems(): { id: number; fsObjType: FileSystemObjectType; }[]; + export function getSelectedItems(): Array<{ id: number; fsObjType: FileSystemObjectType; }>; export function getSelectedList(): string; export function getSelectedView(): string; export function navigateUp(viewId: string): void; export function deselectAllListItems(iid: string): void; } - export module Overrides { + export namespace Overrides { export function overrideDeleteConfirmation(listId: string, overrideText: string): void; } } @@ -191,9 +191,9 @@ declare function AddEvtHandler(element: HTMLElement, event: string, func: EventL declare function GetUrlKeyValue(key: string): string; declare class AjaxNavigate { - update(url: string, updateParts: Object, fullNavigate: boolean, anchorName: string): void; - add_navigate(handler: Function): void; - remove_navigate(handler: Function): void; + update(url: string, updateParts: { [name: string]: string | number }, fullNavigate: boolean, anchorName: string): void; + add_navigate(handler: (obj: any, eventArgs: any) => void): void; + remove_navigate(handler: (obj: any, eventArgs: any) => void): void; submit(formToSubmit: HTMLFormElement): void; getParam(paramName: string): string; getSavedFormAction(): string; @@ -246,7 +246,7 @@ declare class Browseris { win32: boolean; win64bit: boolean; winnt: boolean; - armProcessor: boolean + armProcessor: boolean; } declare var browseris: Browseris; @@ -268,7 +268,7 @@ interface ContextInfo extends SPClientTemplates.RenderContext { LastSelectedItemIID: number; LastRowIndexSelected: number; RowFocusTimerID: number; - ListData: any;// SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm + ListData: any; //SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm ListSchema: SPClientTemplates.ListSchema; ModerationStatus: number; PortalUrl: string; @@ -277,8 +277,8 @@ interface ContextInfo extends SPClientTemplates.RenderContext { SendToLocationName: string; SendToLocationUrl: string; StateInitDone: boolean; - TableCbxFocusHandler: Function; - TableMouseoverHandler: Function; + TableCbxFocusHandler: (instance: any, eventArgs: any) => void; + TableMouseoverHandler: (instance: any, eventArgs: any) => void; TotalListItems: number; WorkflowsAssociated: boolean; clvp: any; @@ -302,7 +302,7 @@ interface ContextInfo extends SPClientTemplates.RenderContext { listTemplate: string; listUrlDir: string; newFormUrl: string; - onRefreshFailed: Function; + onRefreshFailed: (context: any, requrest: any, response: any) => void; overrideDeleteConfirmation: string; overrideFilterQstring: string; recursiveView: boolean; @@ -385,20 +385,16 @@ declare namespace SP { createWebRequestExecutor(): ProxyWebRequestExecutor; } } + interface MQuery { (selector: string, context?: any): MQueryResultSetElements; - (element: HTMLElement): MQueryResultSetElements; - (object: MQueryResultSetElements): MQueryResultSetElements; - (object: MQueryResultSet): MQueryResultSet; - (object: T): MQueryResultSet; - (elementArray: HTMLElement[]): MQueryResultSetElements; - (array: T[]): MQueryResultSet; - (): MQueryResultSet; + (objectOrElement: MQueryResultSetElements | HTMLElement | HTMLElement[]): MQueryResultSetElements; + (object?: MQueryResultSet | T | T[]): MQueryResultSet; - throttle(fn: Function, interval: number, shouldOverrideThrottle: boolean): Function; + throttle any>(fn: T, interval: number, shouldOverrideThrottle: boolean): T; - extend(target: any, ...objs: any[]): Object; - extend(deep: boolean, target: any, ...objs: any[]): Object; + extend(target: any, ...objs: any[]): any; + extend(deep: boolean, target: any, ...objs: any[]): any; makeArray(obj: any): any[]; @@ -422,49 +418,31 @@ interface MQuery { ready(callback: () => void): void; contains(container: HTMLElement, contained: HTMLElement): boolean; - proxy(fn: (...args: any[]) => any, context: any, ...args: any[]): Function; + proxy(fn: (...args: any[]) => any, context: any, ...args: any[]): (...args: any[]) => any; proxy(context: any, name: string, ...args: any[]): any; - every(obj: T[], fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; - every(obj: MQueryResultSet, fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; - every(obj: T[], fn: (elementOfArray: T) => boolean, context?: any): boolean; - every(obj: MQueryResultSet, fn: (elementOfArray: any) => boolean, context?: any): boolean; + every(obj: T[] | MQueryResultSet, fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): boolean; + some(obj: T[] | MQueryResultSet, fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): boolean; - some(obj: T[], fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; - some(obj: MQueryResultSet, fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; - some(obj: T[], fn: (elementOfArray: T) => boolean, context?: any): boolean; - some(obj: MQueryResultSet, fn: (elementOfArray: T) => boolean, context?: any): boolean; + filter(obj: T[], fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): T[]; + filter(obj: MQueryResultSet, fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): MQueryResultSet; - filter(obj: T[], fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): T[]; - filter(obj: MQueryResultSet, fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): MQueryResultSet; - filter(obj: T[], fn: (elementOfArray: T) => boolean, context?: any): T[]; - filter(obj: MQueryResultSet, fn: (elementOfArray: T) => boolean, context?: any): MQueryResultSet; + forEach(obj: T[] | MQueryResultSet, fn: (elementOfArray: T, indexInArray?: number) => void, context?: any): void; - forEach(obj: T[], fn: (elementOfArray: T, indexInArray: number) => void, context?: any): void; - forEach(obj: MQueryResultSet, fn: (elementOfArray: T, indexInArray: number) => void, context?: any): void; - forEach(obj: T[], fn: (elementOfArray: T) => void, context?: any): void; - forEach(obj: MQueryResultSet, fn: (elementOfArray: T) => void, context?: any): void; - - map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; - map(array: MQueryResultSet, callback: (elementOfArray: T, indexInArray: number) => U): MQueryResultSet; - map(array: T[], callback: (elementOfArray: T) => U): U[]; - map(array: MQueryResultSet, callback: (elementOfArray: T) => U): MQueryResultSet; + map(array: T[], callback: (elementOfArray: T, indexInArray?: number) => U): U[]; + map(array: MQueryResultSet, callback: (elementOfArray: T, indexInArray?: number) => U): MQueryResultSet; indexOf(obj: T[], object: T, startIndex?: number): number; lastIndexOf(obj: T[], object: T, startIndex?: number): number; - data(element: HTMLElement, key: string, value: any): any; - data(element: HTMLElement, key: string): any; - data(element: HTMLElement): any; + data(element: HTMLElement, key?: string, value?: any): any; removeData(element: HTMLElement, name?: string): MQueryResultSetElements; hasData(element: HTMLElement): boolean; } interface MQueryResultSetElements extends MQueryResultSet { - append(node: HTMLElement): MQueryResultSetElements; - append(mQuerySet: MQueryResultSetElements): MQueryResultSetElements; - append(html: string): MQueryResultSetElements; + append(node: HTMLElement | MQueryResultSetElements | string): MQueryResultSetElements; bind(eventType: string, handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; unbind(eventType: string, handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; @@ -479,8 +457,7 @@ interface MQueryResultSetElements extends MQueryResultSet { offset(coordinates: { left: any; top: any; }): MQueryResultSetElements; filter(selector: string): MQueryResultSetElements; - filter(fn: (elementOfArray: HTMLElement, indexInArray: number) => boolean, context?: any): MQueryResultSetElements; - filter(fn: (elementOfArray: HTMLElement) => boolean, context?: any): MQueryResultSetElements; + filter(fn: (elementOfArray: HTMLElement, indexInArray?: number) => boolean, context?: any): MQueryResultSetElements; not(selector: string): MQueryResultSetElements; @@ -489,24 +466,22 @@ interface MQueryResultSetElements extends MQueryResultSet { offsetParent(selector?: string): MQueryResultSetElements; parents(selector?: string): MQueryResultSetElements; - parentsUntil(selector?: string, filter?: string): MQueryResultSetElements; - parentsUntil(element?: HTMLElement, filter?: string): MQueryResultSetElements; + parentsUntil(selectorOrElement?: string | HTMLElement, filter?: string): MQueryResultSetElements; position(): { top: number; left: number; }; attr(attributeName: string): string; - attr(attributeName: string, value: any): MQueryResultSetElements; + attr(attributeName: string, valueOrDelegate: any): MQueryResultSetElements; attr(map: { [key: string]: any; }): MQueryResultSetElements; + // tslint:disable-next-line: unified-signatures attr(attributeName: string, func: (index: number, attr: any) => any): MQueryResultSetElements; addClass(classNames: string): MQueryResultSetElements; removeClass(classNames: string): MQueryResultSetElements; - css(propertyName: string): string; - css(propertyNames: string[]): string; + css(propertyName: string | string[]): string; css(properties: any): MQueryResultSetElements; - css(propertyName: string, value: any): MQueryResultSetElements; - css(propertyName: any, value: any): MQueryResultSetElements; + css(propertyName: any | string, value: any): MQueryResultSetElements; remove(selector?: string): MQueryResultSetElements; children(selector?: string): MQueryResultSetElements; @@ -519,82 +494,45 @@ interface MQueryResultSetElements extends MQueryResultSet { removeData(key: string): MQueryResultSetElements; - map(callback: (elementOfArray: HTMLElement, indexInArray: number) => any): MQueryResultSetElements; - map(callback: (elementOfArray: HTMLElement) => any): MQueryResultSetElements; + map(callback?: (elementOfArray: HTMLElement, indexInArray: number) => any): MQueryResultSetElements; - blur(): MQueryResultSetElements; - blur(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - change(): MQueryResultSetElements; - change(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - click(): MQueryResultSetElements; - click(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - dblclick(): MQueryResultSetElements; - dblclick(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - error(): MQueryResultSetElements; - error(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - focus(): MQueryResultSetElements; + blur(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + change(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + click(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + dblclick(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + error(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; focus(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - focusin(): MQueryResultSetElements; - focusin(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - focusout(): MQueryResultSetElements; - focusout(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - keydown(): MQueryResultSetElements; - keydown(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - keypress(): MQueryResultSetElements; - keypress(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - keyup(): MQueryResultSetElements; - keyup(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - load(): MQueryResultSetElements; - load(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mousedown(): MQueryResultSetElements; - mousedown(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mouseenter(): MQueryResultSetElements; - mouseenter(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mouseleave(): MQueryResultSetElements; - mouseleave(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mousemove(): MQueryResultSetElements; - mousemove(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mouseout(): MQueryResultSetElements; - mouseout(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mouseover(): MQueryResultSetElements; - mouseover(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - mouseup(): MQueryResultSetElements; - mouseup(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - resize(): MQueryResultSetElements; - resize(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - scroll(): MQueryResultSetElements; - scroll(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - select(): MQueryResultSetElements; - select(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - submit(): MQueryResultSetElements; - submit(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - unload(): MQueryResultSetElements; - unload(handler: (eventObject: MQueryEvent) => any): MQueryResultSetElements; - + focusin(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + focusout(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + keydown(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + keypress(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + keyup(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + load(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mousedown(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mouseenter(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mouseleave(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mousemove(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mouseout(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mouseover(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + mouseup(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + resize(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + scroll(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + select(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + submit(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; + unload(handler?: (eventObject: MQueryEvent) => any): MQueryResultSetElements; } interface MQueryResultSet { [index: number]: T; contains(contained: T): boolean; - filter(fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): MQueryResultSet; - filter(fn: (elementOfArray: T) => boolean, context?: any): MQueryResultSet; - - every(fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; - every(fn: (elementOfArray: T) => boolean, context?: any): boolean; - - some(fn: (elementOfArray: T, indexInArray: number) => boolean, context?: any): boolean; - some(fn: (elementOfArray: T) => boolean, context?: any): boolean; - - map(callback: (elementOfArray: T, indexInArray: number) => any): MQueryResultSet; - map(callback: (elementOfArray: T) => any): MQueryResultSet; - - forEach(fn: (elementOfArray: T, indexInArray: number) => void, context?: any): void; - forEach(fn: (elementOfArray: T) => void, context?: any): void; - + filter(fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): MQueryResultSet; + every(fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): boolean; + some(fn: (elementOfArray: T, indexInArray?: number) => boolean, context?: any): boolean; + map(callback: (elementOfArray: T, indexInArray?: number) => any): MQueryResultSet; + forEach(fn: (elementOfArray: T, indexInArray?: number) => void, context?: any): void; indexOf(object: any, startIndex?: number): number; lastIndexOf(object: any, startIndex?: number): number; - } interface MQueryEvent extends Event { @@ -883,7 +821,7 @@ declare namespace SPClientTemplates { Only appears if Throttled property is true, i.e. the target lookup list is throttled. */ MaxQueryResult: string; /** List of choices for this field. */ - Choices: { LookupId: number; LookupValue: string; }[]; + Choices: Array<{ LookupId: number; LookupValue: string; }>; /** Number of choices. Appears only for Lookup field. */ ChoiceCount: number; @@ -1305,32 +1243,23 @@ declare namespace SPClientTemplates { Templates?: Templates; } - export interface SingleTemplateCallback { - /** Must return null in order to fall back to a more common template or to a system default template */ - (renderContext: RenderContext_InView): string; - } - export interface GroupCallback { - /** Must return null in order to fall back to a more common template or to a system default template */ - (renderContext: RenderContext_GroupInView): string; - } - export interface ItemCallback { - /** Must return null in order to fall back to a more common template or to a system default template */ - (renderContext: RenderContext): string; - } + /** Must return null in order to fall back to a more common template or to a system default template */ + export type SingleTemplateCallback = (renderContext: RenderContext_InView) => string; - export interface FieldCallback { - /** Must return null in order to fall back to a more common template or to a system default template */ - (renderContext: RenderContext): string; - } + /** Must return null in order to fall back to a more common template or to a system default template */ + export type GroupCallback = (renderContext: RenderContext_GroupInView) => string; - export interface FieldInFormCallback { - /** Must return null in order to fall back to a more common template or to a system default template */ - (renderContext: RenderContext_FieldInForm): string; - } - export interface FieldInViewCallback { - /** Must return null in order to fall back to a more common template or to a system default template */ - (renderContext: RenderContext_FieldInView): string; - } + /** Must return null in order to fall back to a more common template or to a system default template */ + export type ItemCallback = (renderContext: RenderContext) => string; + + /** Must return null in order to fall back to a more common template or to a system default template */ + export type FieldCallback = (renderContext: RenderContext) => string; + + /** Must return null in order to fall back to a more common template or to a system default template */ + export type FieldInFormCallback = (renderContext: RenderContext_FieldInForm) => string; + + /** Must return null in order to fall back to a more common template or to a system default template */ + export type FieldInViewCallback = (renderContext: RenderContext_FieldInView) => string; export interface FieldTemplateOverrides { /** Defines templates for rendering the field on a display form. */ @@ -1455,7 +1384,7 @@ declare namespace SPClientTemplates { /** Returns ";#" */ static UserLookupDelimitString: string; /** Returns ";#" */ - static UserMultiValueDelimitString:string; + static UserMultiValueDelimitString: string; } export class ClientFormContext { @@ -1508,9 +1437,9 @@ declare namespace SPClientForms { } export class ValidatorSet { - public RegisterValidator(validator: IValidator): void; + RegisterValidator(validator: IValidator): void; } - + // tslint:disable-next-line: interface-name export interface IValidator { Validate(value: any): ValidationResult; } @@ -1535,13 +1464,13 @@ declare namespace SPClientForms { } export enum FormManagerEvents { - Event_OnControlValueChanged,//: 1, - Event_OnControlInitializedCallback,//: 2, - Event_OnControlFocusSetCallback,//: 3, - Event_GetControlValueCallback,//: 4, - Event_OnControlValidationError,//: 5, - Event_RegisterControlValidator,//: 6, - Event_GetHasValueChangedCallback//: 7 + Event_OnControlValueChanged, //: 1, + Event_OnControlInitializedCallback, //: 2, + Event_OnControlFocusSetCallback, //: 3, + Event_GetControlValueCallback, //: 4, + Event_OnControlValidationError, //: 5, + Event_RegisterControlValidator, //: 6, + Event_GetHasValueChangedCallback //: 7 } export class ClientForm { @@ -1559,10 +1488,10 @@ declare namespace SPClientForms { } declare class SPMgr { - NewGroup(listItem: Object, fieldName: string): boolean; + NewGroup(listItem: { [name: string]: any }, fieldName: string): boolean; RenderHeader(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema): string; - RenderField(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; - RenderFieldByName(renderCtx: SPClientTemplates.RenderContext, fieldName: string, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; + RenderField(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema, listItem: { [name: string]: any }, listSchema: SPClientTemplates.ListSchema): string; + RenderFieldByName(renderCtx: SPClientTemplates.RenderContext, fieldName: string, listItem: { [name: string]: any }, listSchema: SPClientTemplates.ListSchema): string; } declare var spMgr: SPMgr; @@ -1641,8 +1570,7 @@ declare namespace SPAnimation { } export class Object { - constructor(animationID: ID, delay: number, element: HTMLElement, finalState: State, finishFunc?: (data: any) => void, data?: any); - constructor(animationID: ID, delay: number, element: HTMLElement[], finalState: State, finishFunc?: (data: any) => void, data?: any); + constructor(animationID: ID, delay: number, element: HTMLElement | HTMLElement[], finalState: State, finishFunc?: (data: any) => void, data?: any); RunAnimation(): void; } } @@ -1670,12 +1598,14 @@ declare namespace SPAnimationUtility { } } +// tslint:disable-next-line: interface-name interface IEnumerator { get_current(): T; moveNext(): boolean; reset(): void; } +// tslint:disable-next-line: interface-name interface IEnumerable { getEnumerator(): IEnumerator; } @@ -1692,8 +1622,7 @@ declare namespace SP { static get_empty(): SP.Guid; static newGuid(): SP.Guid; static isValid(uuid: string): boolean; - toString(): string; - toString(format: string): string; + toString(format?: string): string; equals(uuid: SP.Guid): boolean; toSerialized(): string; } @@ -1781,13 +1710,13 @@ declare namespace SP { itemAtIndex(index: number): T; constructor(); } + // tslint:disable-next-line: interface-name export interface IFromJson { fromJson(initValue: any): void; customFromJson(initValue: any): boolean; } export class Base64EncodedByteArray { - constructor(); - constructor(base64Str: string); + constructor(base64Str?: string); get_length(): number; toBase64String(): string; append(b: any): void; @@ -1803,8 +1732,7 @@ declare namespace SP { customFromJson(initValue: any): boolean; } export class ClientObjectPropertyConditionalScope extends SP.ConditionalScopeBase { - constructor(clientObject: SP.ClientObject, propertyName: string, comparisonOperator: string, valueToCompare: any); - constructor(clientObject: SP.ClientObject, propertyName: string, comparisonOperator: string, valueToCompare: any, allowAllActions: boolean); + constructor(clientObject: SP.ClientObject, propertyName: string, comparisonOperator: string, valueToCompare: any, allowAllActions?: boolean); } //export class ClientResult { // get_value(): any; @@ -1890,6 +1818,8 @@ declare namespace SP { static createUtcDateTime(milliseconds: number): Date; static createLocalDateTime(milliseconds: number): Date; } + + // tslint:disable-next-line: interface-name export interface IWebRequestExecutorFactory { createWebRequestExecutor(): Sys.Net.WebRequestExecutor; } @@ -2114,9 +2044,8 @@ declare namespace SP { set_objectVersion(value: string): void; fromJson(initValue: any): void; customFromJson(initValue: any): boolean; - retrieve(): void; refreshLoad(): void; - retrieve(propertyNames: string[]): void; + retrieve(propertyNames?: string[]): void; isPropertyAvailable(propertyName: string): boolean; isObjectPropertyInstantiated(propertyName: string): boolean; get_serverObjectIsNull(): boolean; @@ -2144,14 +2073,14 @@ declare namespace SP { getItemAtIndex(index: number): T; fromJson(obj: any): void; } + export class ClientObjectList extends SP.ClientObjectCollection { constructor(context: SP.ClientRuntimeContext, objectPath: SP.ObjectPath, childItemType: any); fromJson(initValue: any): void; customFromJson(initValue: any): boolean; } export class ClientObjectPrototype { - retrieve(): void; - retrieve(propertyNames: string[]): void; + retrieve(propertyNames?: string[]): void; retrieveObject(propertyName: string): SP.ClientObjectPrototype; retrieveCollectionObject(propertyName: string): SP.ClientObjectCollectionPrototype; } @@ -2182,8 +2111,7 @@ declare namespace SP { get_request(): SP.ClientRequest; } export class ClientRequestFailedEventArgs extends SP.ClientRequestEventArgs { - constructor(request: SP.ClientRequest, message: string, stackTrace: string, errorCode: number, errorValue: string, errorTypeName: string, errorDetails: any); - constructor(request: SP.ClientRequest, message: string, stackTrace: string, errorCode: number, errorValue: string, errorTypeName: string, errorDetails: any, errorTraceCorrelationId: string); + constructor(request: SP.ClientRequest, message: string, stackTrace: string, errorCode: number, errorValue: string, errorTypeName: string, errorDetails: any, errorTraceCorrelationId?: string); get_message(): string; get_stackTrace(): string; get_errorCode(): number; @@ -2219,19 +2147,14 @@ declare namespace SP { remove_beginningRequest(value: (sender: any, args: SP.ClientRequestEventArgs) => void): void; get_requestTimeout(): number; set_requestTimeout(value: number): void; - executeQueryAsync(succeededCallback: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void, failedCallback: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; - executeQueryAsync(succeededCallback: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void): void; - executeQueryAsync(): void; + executeQueryAsync(succeededCallback?: (sender: any, args: SP.ClientRequestSucceededEventArgs) => void, failedCallback?: (sender: any, args: SP.ClientRequestFailedEventArgs) => void): void; get_staticObjects(): any; castTo(obj: SP.ClientObject, type: any): SP.ClientObject; addQuery(query: SP.ClientAction): void; addQueryIdAndResultObject(id: number, obj: any): void; - parseObjectFromJsonString(json: string): any; - parseObjectFromJsonString(json: string, skipTypeFixup: boolean): any; - load(clientObject: SP.ClientObject): void; - loadQuery(clientObjectCollection: SP.ClientObjectCollection, exp: string): any; + parseObjectFromJsonString(json: string, skipTypeFixup?: boolean): any; load(clientObject: SP.ClientObject, ...exps: string[]): void; - loadQuery(clientObjectCollection: SP.ClientObjectCollection): any; + loadQuery(clientObjectCollection: SP.ClientObjectCollection, exp?: string): any; get_serverSchemaVersion(): string; get_serverLibraryVersion(): string; get_traceCorrelationId(): string; @@ -2438,9 +2361,8 @@ declare namespace SP { wssMajorVersion: string; } export class ClientContext extends SP.ClientRuntimeContext { - constructor(serverRelativeUrlOrFullUrl: string); + constructor(serverRelativeUrlOrFullUrl?: string); static get_current(): SP.ClientContext; - constructor(); get_web(): SP.Web; get_site(): SP.Site; get_serverVersion(): string; @@ -2462,9 +2384,7 @@ declare namespace SP { /** Decreases the indentation for subsequent log messages. */ static decreaseIndent(): void; /** Traces when the function was entered. */ - static traceApiEnter(functionName: string, args: any[]): void; - /** Traces when the function was entered. */ - static traceApiEnter(functionName: string): void; + static traceApiEnter(functionName: string, args?: any[]): void; /** Traces when the function has finished. */ static traceApiLeave(): void; } @@ -3861,9 +3781,7 @@ declare namespace SP { /** Returns the list with the specified title from the collection. */ getByTitle(title: string): SP.List; /** Returns the list with the specified list identifier. */ - getById(id: SP.Guid): SP.List; - /** Returns the list with the specified list identifier. */ - getById(id: string): SP.List; + getById(id: string | SP.Guid): SP.List; /** Creates a new list or a document library. */ add(parameters: SP.ListCreationInformation): SP.List; /** Gets a list that is the default location for wiki pages. */ @@ -3981,8 +3899,7 @@ declare namespace SP { export class ListItemCollection extends SP.ClientObjectCollection { itemAt(index: number): SP.ListItem; get_item(index: number): SP.ListItem; - getById(id: number): SP.ListItem; - getById(id: string): SP.ListItem; + getById(id: number | string): SP.ListItem; get_listItemCollectionPosition(): SP.ListItemCollectionPosition; } export class ListItemCollectionPosition extends SP.ClientValueObject { @@ -4975,8 +4892,8 @@ declare namespace SP { getByName(name: string): SP.WebTemplate; } - export module Application { - export module UI { + export namespace Application { + export namespace UI { export interface DefaultFormsInformationRequestor { onDefaultFormsInformationRetrieveSuccess(defaultForms: SP.Application.UI.DefaultFormsInformation): void; onDefaultFormsInformationRetrieveFailure(): void; @@ -5077,7 +4994,7 @@ declare namespace SP { } - export module Analytics { + export namespace Analytics { export class AnalyticsUsageEntry extends SP.ClientObject { static logAnalyticsEvent(context: SP.ClientRuntimeContext, eventTypeId: number, itemId: string): void; static logAnalyticsEvent2(context: SP.ClientRuntimeContext, eventTypeId: number, itemId: string, rollupScopeId: SP.Guid, siteId: SP.Guid, userId: string): void; @@ -5094,7 +5011,7 @@ declare namespace SP { } } - export module SiteHealth { + export namespace SiteHealth { export class SiteHealthResult extends SP.ClientValueObject { get_messageAsText(): string; get_ruleHelpLink(): string; @@ -5312,7 +5229,7 @@ declare namespace Microsoft.SharePoint.Client.Search { constructor(context: SP.ClientContext); itemAt: (index: number) => string; get_item: (index: number) => string; - get_childItemType: () => Object; + get_childItemType: () => typeof String; add: (property: string) => void; clear: () => void; } @@ -5392,7 +5309,7 @@ declare namespace Microsoft.SharePoint.Client.Search { export class ReorderingRuleCollection extends SP.ClientObjectCollection { itemAt: (index: number) => ReorderingRule; get_item: (index: number) => ReorderingRule; - get_childItemType: () => Object; + get_childItemType: () => typeof ReorderingRule; add: (property: ReorderingRule) => void; clear: () => void; } @@ -5423,7 +5340,7 @@ declare namespace Microsoft.SharePoint.Client.Search { export class SortCollection extends SP.ClientObjectCollection { itemAt: (index: number) => Sort; get_item: (index: number) => Sort; - get_childItemType: () => Object; + get_childItemType: () => typeof Sort; add: (strProperty: string, sortDirection: SortDirection) => void; clear: () => void; } @@ -5473,7 +5390,7 @@ declare namespace Microsoft.SharePoint.Client.Search { get_queryRuleId: () => string; - get_resultRows: () => { [key: string]: any; }[]; + get_resultRows: () => Array<{ [key: string]: any; }>; get_resultTitle: () => string; @@ -5644,7 +5561,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class SearchConfigurationPortabilityPropertyNames { - static importWarnings: string;// = 'ImportWarnings' + static importWarnings: string; //= 'ImportWarnings' } } @@ -5682,7 +5599,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } declare namespace SP { - export module BusinessData { + export namespace BusinessData { export class AppBdcCatalog extends SP.ClientObject { getEntity(namespace: string, name: string): SP.BusinessData.Entity; getLobSystemProperty(lobSystemName: string, propertyName: string): SP.StringResult; @@ -5776,7 +5693,7 @@ declare namespace SP { getChildTypeDescriptors(): SP.BusinessData.Collections.TypeDescriptorCollection; getParentTypeDescriptor(): SP.BusinessData.TypeDescriptor; } - export module Collections { + export namespace Collections { export class EntityFieldCollection extends SP.ClientObjectCollection { itemAt(index: number): SP.BusinessData.EntityField; get_item(index: number): SP.BusinessData.EntityField; @@ -5804,7 +5721,7 @@ declare namespace SP { } } - export module Infrastructure { + export namespace Infrastructure { export class ExternalSubscriptionStore extends SP.ClientObject { constructor(context: SP.ClientRuntimeContext, web: SP.Web); static newObject(context: SP.ClientRuntimeContext, web: SP.Web): SP.BusinessData.Infrastructure.ExternalSubscriptionStore; @@ -5812,7 +5729,7 @@ declare namespace SP { } } - export module Runtime { + export namespace Runtime { export enum EntityEventType { none, itemAdded, @@ -5871,7 +5788,7 @@ declare namespace SP { } declare namespace SP { - export module Sharing { + export namespace Sharing { export class DocumentSharingManager { static getRoleDefinition(context: SP.ClientRuntimeContext, role: SP.Sharing.Role): SP.RoleDefinition; static isDocumentSharingEnabled(context: SP.ClientRuntimeContext, list: SP.List): SP.BooleanResult; @@ -5909,7 +5826,7 @@ declare namespace SP { declare namespace SP { - export module Social { + export namespace Social { /** Identifies an actor as a user, document, site, or tag. */ export enum SocialActorType { user, @@ -6637,8 +6554,7 @@ declare namespace SP { addLanguage(lcid: number): void; commitAll(): void; - createGroup(name: string): TermGroup; - createGroup(name: string, groupId: SP.Guid): TermGroup; + createGroup(name: string, groupId?: SP.Guid): TermGroup; deleteLanguage(lcid: number): void; @@ -6734,9 +6650,8 @@ declare namespace SP { getAllTerms(): TermCollection; getChanges(changeInformation: ChangeInformation): ChangedItemCollection; getTerm(termId: SP.Guid): Term; - getTerms(pagingLimit: number): TermCollection; + getTerms(pagingLimit: number | LabelMatchInformation): TermCollection; getTerms(termLabel: string, trimUnavailable: boolean): TermCollection; - getTerms(labelMatchInformation: LabelMatchInformation): TermCollection; getTermsWithCustomProperty(customPropertyName: string, trimUnavailable: boolean): TermCollection; getTermsWithCustomProperty(customPropertyMatchInformation: CustomPropertyMatchInformation): TermCollection; move(targetGroup: TermGroup): void; @@ -6961,40 +6876,40 @@ declare namespace SP { } declare namespace SP { - export module DocumentSet { + export namespace DocumentSet { export class DocumentSet extends ClientObject { static create(context: ClientContext, parentFolder: Folder, name: string, ctid: ContentTypeId): StringResult; } } - export module Video { + export namespace Video { export class EmbedCodeConfiguration extends ClientValueObject { - public get_autoPlay(): boolean; - public set_autoPlay(value: boolean): boolean; + get_autoPlay(): boolean; + set_autoPlay(value: boolean): boolean; - public get_displayTitle(): boolean; - public set_displayTitle(value: boolean): boolean; + get_displayTitle(): boolean; + set_displayTitle(value: boolean): boolean; - public get_linkToOwnerProfilePage(): boolean; - public set_linkToOwnerProfilePage(value: boolean): boolean; + get_linkToOwnerProfilePage(): boolean; + set_linkToOwnerProfilePage(value: boolean): boolean; - public get_linkToVideoHomePage(): boolean; - public set_linkToVideoHomePage(value: boolean): boolean; + get_linkToVideoHomePage(): boolean; + set_linkToVideoHomePage(value: boolean): boolean; - public get_loop(): boolean; - public set_loop(value: boolean): boolean; + get_loop(): boolean; + set_loop(value: boolean): boolean; - public get_pixelHeight(): number; - public set_pixelHeight(value: number): number; + get_pixelHeight(): number; + set_pixelHeight(value: number): number; - public get_pixelWidth(): number; - public set_pixelWidth(value: number): number; + get_pixelWidth(): number; + set_pixelWidth(value: number): number; - public get_startTime(): number; - public set_startTime(value: number): number; + get_startTime(): number; + set_startTime(value: number): number; - public get_previewImagePath(): string; - public set_previewImagePath(value: string): string; + get_previewImagePath(): string; + set_previewImagePath(value: string): string; } export class VideoSet extends DocumentSet.DocumentSet { @@ -7008,12 +6923,13 @@ declare namespace SP { declare namespace SP { - export module UI { - export module ApplicationPages { + export namespace UI { + export namespace ApplicationPages { export class SelectorSelectionEventArgs extends Sys.EventArgs { constructor(entities: any); get_entities(): any; } + // tslint:disable-next-line: interface-name export interface ISelectorComponent { get_selectedEntities(): any; set_selectedEntities(value: any): void; @@ -7053,6 +6969,8 @@ declare namespace SP { removeEntity(ent: SP.UI.ApplicationPages.ResolveEntity): void; setEntity(ent: SP.UI.ApplicationPages.ResolveEntity): void; } + + // tslint:disable-next-line: interface-name export interface ICalendarController { moveToDate(date: string): void; moveToViewType(viewType: string): void; @@ -7142,7 +7060,7 @@ declare namespace SP { } declare namespace SP { - export module UI { + export namespace UI { export class PopoutMenu implements Sys.IDisposable { constructor(launcherId: string, menuId: string, iconId: string, launcherOpenCssClass: string, textDirection: string, closeIconUrl: string, isClustered: boolean, closeIconOffsetLeft: number, closeIconOffsetTop: number, closeIconHeight: number, closeIconWidth: number); launchMenu(): void; @@ -7164,7 +7082,7 @@ declare namespace SP { constructor(); } - export module Notify { + export namespace Notify { export function addNotification(strHtml: string, bSticky: boolean): string; export function removeNotification(nid: string): void; export function showLoadingNotification(bSticky: boolean): string; @@ -7194,7 +7112,7 @@ declare namespace SP { constructor(); } - export module Workspace { + export namespace Workspace { export function add_resized(handler: () => void): void; export function remove_resized(handler: () => void): void; } @@ -7225,10 +7143,9 @@ declare namespace SP { OK } /** Callback which processes dialog result value after dialog is closed */ - export interface DialogReturnValueCallback { - (dialogResult: DialogResult, returnValue: any): void; - } + export type DialogReturnValueCallback = (dialogResult: DialogResult, returnValue: any) => void; /** Options for dialog creation */ + // tslint:disable-next-line: interface-name export interface IDialogOptions { /** Text displayed in the title bar of the dialog box. If not defined, it will default to the title of the page defined by url property. */ title?: string; @@ -7404,21 +7321,21 @@ declare namespace SP { static ButtonIDs: { prev: number; next: number; - } + }; static ButtonState: { - hidden: number + hidden: number; disabled: number; enabled: number; - } + }; } - export module Workplace { - export function add_resized(handler: Function): void; - export function remove_resized(handler: Function): void; + export namespace Workplace { + export function add_resized(handler: (obj: any, args: any) => void): void; + export function remove_resized(handler: (obj: any, args: any) => void): void; } - export module UIUtility { + export namespace UIUtility { export function generateRandomElementId(): string; export function cancelEvent(evt: Event): void; export function clearChildNodes(elem: HTMLElement): void; @@ -7459,12 +7376,13 @@ declare namespace SPNotifications { declare class SPStatusNotificationData { constructor(text: string, subText: string, imageUrl: string, sip: string); } -declare function RefreshCommandUI():void; +declare function RefreshCommandUI(): void; declare namespace SP { - export module UI { - export module Controls { + export namespace UI { + export namespace Controls { + // tslint:disable-next-line: interface-name export interface INavigationOptions { assetId?: string; siteTitle?: string; @@ -7490,6 +7408,7 @@ declare namespace SP { export class NavigationOptions implements INavigationOptions { } + // tslint:disable-next-line: interface-name export interface ISettingsLink { linkUrl: string; displayName: string; @@ -7503,39 +7422,39 @@ declare namespace SP { export class Navigation { constructor(placeholderDOMElementId: string, options: INavigationOptions); - public get_assetId(): string; - public get_siteTitle(): string; - public get_siteUrl(): string; + get_assetId(): string; + get_siteTitle(): string; + get_siteUrl(): string; - public get_appTitle(): string; - public set_appTitle(value: string): string; + get_appTitle(): string; + set_appTitle(value: string): string; - public get_appTitleIconUrl(): string; - public set_appTitleIconUrl(value: string): string; + get_appTitleIconUrl(): string; + set_appTitleIconUrl(value: string): string; - public get_rightToLeft(): boolean; - public set_rightToLeft(value: boolean): boolean; + get_rightToLeft(): boolean; + set_rightToLeft(value: boolean): boolean; - public get_appStartPage(): string; - public set_appStartPage(value: string): string; + get_appStartPage(): string; + set_appStartPage(value: string): string; - public get_appIconUrl(): string; - public set_appIconUrl(value: string): string; + get_appIconUrl(): string; + set_appIconUrl(value: string): string; - public get_appHelpPageUrl(): string; - public set_appHelpPageUrl(value: string): string; + get_appHelpPageUrl(): string; + set_appHelpPageUrl(value: string): string; - public get_appHelpPageOnClick(): string; - public set_appHelpPageOnClick(value: string): string; + get_appHelpPageOnClick(): string; + set_appHelpPageOnClick(value: string): string; - public get_settingsLinks(): ISettingsLink[]; - public set_settingsLinks(value: ISettingsLink[]): ISettingsLink[]; + get_settingsLinks(): ISettingsLink[]; + set_settingsLinks(value: ISettingsLink[]): ISettingsLink[]; - public setVisible(value: boolean): void; + setVisible(value: boolean): void; - public setTopHeaderVisible(value: boolean): void; - public setBottomHeaderVisible(value: boolean): void; - public remove(): void; + setTopHeaderVisible(value: boolean): void; + setBottomHeaderVisible(value: boolean): void; + remove(): void; static getVersionedLayoutsUrl(pageName: string): string; } @@ -7550,7 +7469,7 @@ declare namespace SP { declare namespace SP { - export module UserProfiles { + export namespace UserProfiles { /** Specifies types of changes made in the user profile store. */ export enum ChangeTypes { /** No change was made */ @@ -7979,7 +7898,7 @@ declare namespace SP { declare namespace SP { - export module Utilities { + export namespace Utilities { export class Utility { lAYOUTS_LATESTVERSION_RELATIVE_URL: string; lAYOUTS_LATESTVERSION_URL: string; @@ -8137,7 +8056,7 @@ declare namespace SP { } - export module DateTimeUtil { + export namespace DateTimeUtil { export class SimpleDate { constructor(year: number, month: number, day: number, era: number); get_year(): number; @@ -8158,7 +8077,7 @@ declare namespace SP { } declare namespace SP { - export module WebParts { + export namespace WebParts { export class LimitedWebPartManager extends SP.ClientObject { get_hasPersonalizedParts(): boolean; get_scope(): SP.WebParts.PersonalizationScope; @@ -8218,7 +8137,7 @@ declare namespace SP { } declare namespace SP { - export module Workflow { + export namespace Workflow { export class WorkflowAssociation extends SP.ClientObject { get_allowManual(): boolean; set_allowManual(value: boolean): void; @@ -8616,41 +8535,40 @@ declare namespace SP.WorkflowServices { declare namespace SP { - export module Publishing { + export namespace Publishing { export class PublishingWeb extends ClientObject { static getPublishingWeb(context: ClientContext, web: Web): PublishingWeb; - public get_web(): Web; - public addPublishingPage(pageInformation: PublishingPageInformation): PublishingPage; + get_web(): Web; + addPublishingPage(pageInformation: PublishingPageInformation): PublishingPage; } export class PublishingPageInformation extends ClientValueObject { + get_folder(): Folder; + set_folder(value: Folder): Folder; - public get_folder(): Folder; - public set_folder(value: Folder): Folder; + get_name(): string; + set_name(value: string): string; - public get_name(): string; - public set_name(value: string): string; - - public get_pageLayoutListItem(): ListItem; - public set_pageLayoutListItem(value: ListItem): ListItem; + get_pageLayoutListItem(): ListItem; + set_pageLayoutListItem(value: ListItem): ListItem; } export class PublishingPage extends ScheduledItem { static getPublishingPage(context: ClientContext, sourceListItem: ListItem): PublishingPage; - public addFriendlyUrl(friendlyUrlSegment: string, editableParent: Navigation.NavigationTermSetItem, doAddToNavigation: boolean): StringResult; + addFriendlyUrl(friendlyUrlSegment: string, editableParent: Navigation.NavigationTermSetItem, doAddToNavigation: boolean): StringResult; } export class ScheduledItem extends ClientObject { - public get_listItem(): ListItem; + get_listItem(): ListItem; - public get_startDate(): Date; - public set_startDate(value: Date): Date; + get_startDate(): Date; + set_startDate(value: Date): Date; - public get_endDate(): Date; - public set_endDate(value: Date): Date; + get_endDate(): Date; + set_endDate(value: Date): Date; - public schedule(approvalComment: string): void; + schedule(approvalComment: string): void; } export class PublishingSite extends ClientObject { @@ -8658,20 +8576,20 @@ declare namespace SP { } export class PageLayoutCreationInformation extends ClientValueObject { - public get_web(): Web; - public set_web(value: Web): Web; + get_web(): Web; + set_web(value: Web): Web; - public get_associatedContentTypeId(): string; - public set_associatedContentTypeId(value: string): string; + get_associatedContentTypeId(): string; + set_associatedContentTypeId(value: string): string; - public get_masterPageUrl(): string; - public set_masterPageUrl(value: string): string; + get_masterPageUrl(): string; + set_masterPageUrl(value: string): string; - public get_newPageLayoutNameWithoutExtension(): string; - public set_newPageLayoutNameWithoutExtension(value: string): string; + get_newPageLayoutNameWithoutExtension(): string; + set_newPageLayoutNameWithoutExtension(value: string): string; - public get_newPageLayoutEditablePath(): string; - public set_newPageLayoutEditablePath(value: string): string; + get_newPageLayoutEditablePath(): string; + set_newPageLayoutEditablePath(value: string): string; } export class SiteServicesAddins { @@ -8687,45 +8605,45 @@ declare namespace SP { export class AddinSettings extends ClientObject { constructor(ctx: ClientContext, id: Guid); - public get_id(): Guid; + get_id(): Guid; - public get_title(): string; - public set_title(value: string): string; + get_title(): string; + set_title(value: string): string; - public get_description(): string; - public set_description(value: string): string; + get_description(): string; + set_description(value: string): string; - public get_enabled(): boolean; - public set_enabled(value: boolean): boolean; + get_enabled(): boolean; + set_enabled(value: boolean): boolean; - public get_namespace(): boolean; - public set_namespace(value: boolean): boolean; + get_namespace(): boolean; + set_namespace(value: boolean): boolean; - public get_headScript(): string; - public set_headScript(value: string): string; + get_headScript(): string; + set_headScript(value: string): string; - public get_htmlStartBody(): string; - public set_htmlStartBody(value: string): string; + get_htmlStartBody(): string; + set_htmlStartBody(value: string): string; - public get_htmlEndBody(): string; - public set_htmlEndBody(value: string): string; + get_htmlEndBody(): string; + set_htmlEndBody(value: string): string; - public get_metaTagPagePropertyMappings(): { [key: string]: string }; - public set_metaTagPagePropertyMappings(value: { [key: string]: string }): { [key: string]: string }; + get_metaTagPagePropertyMappings(): { [key: string]: string }; + set_metaTagPagePropertyMappings(value: { [key: string]: string }): { [key: string]: string }; } export class AddinPlugin extends ClientObject { constructor(ctx: ClientContext); - public get_description(): string; - public set_description(value: string): string; + get_description(): string; + set_description(value: string): string; - public get_markup(): string; - public set_markup(value: string): string; + get_markup(): string; + set_markup(value: string): string; - public get_title(): string; - public set_title(value: string): string; + get_title(): string; + set_title(value: string): string; } @@ -8738,17 +8656,17 @@ declare namespace SP { } export class DesignPackageInfo extends ClientValueObject { - public get_packageName(): string; - public set_packageName(value: string): string; + get_packageName(): string; + set_packageName(value: string): string; - public get_packageGuid(): Guid; - public set_packageGuid(value: Guid): Guid; + get_packageGuid(): Guid; + set_packageGuid(value: Guid): Guid; - public get_majorVersion(): number; - public set_majorVersion(value: number): number; + get_majorVersion(): number; + set_majorVersion(value: number): number; - public get_minorVersion(): number; - public set_minorVersion(value: number): number; + get_minorVersion(): number; + set_minorVersion(value: number): number; } export class SiteImageRenditions { @@ -8757,17 +8675,17 @@ declare namespace SP { } export class ImageRendition extends ClientValueObject { - public get_id(): number; - public get_version(): number; + get_id(): number; + get_version(): number; - public get_name(): string; - public set_name(value: string): string; + get_name(): string; + set_name(value: string): string; - public get_width(): number; - public set_width(value: number): number; + get_width(): number; + set_width(value: number): number; - public get_height(): number; - public set_height(value: number): number; + get_height(): number; + set_height(value: number): number; } export class Variations extends ClientObject { @@ -8777,38 +8695,38 @@ declare namespace SP { } export class VariationLabel extends ClientObject { - public get_displayName(): string; - public set_displayName(value: string): string; + get_displayName(): string; + set_displayName(value: string): string; - public get_isSource(): boolean; - public set_isSource(value: boolean): boolean; + get_isSource(): boolean; + set_isSource(value: boolean): boolean; - public get_language(): string; - public set_language(value: string): string; + get_language(): string; + set_language(value: string): string; - public get_locale(): string; - public set_locale(value: string): string; + get_locale(): string; + set_locale(value: string): string; - public get_title(): string; - public set_title(value: string): string; + get_title(): string; + set_title(value: string): string; - public get_topWebUrl(): string; - public set_topWebUrl(value: string): string; + get_topWebUrl(): string; + set_topWebUrl(value: string): string; } export class CustomizableString extends ClientObject { - public get_defaultValue(): string; + get_defaultValue(): string; - public get_value(): string; - public set_value(value: string): string; + get_value(): string; + set_value(value: string): string; - public get_usesDefaultValue(): boolean; - public set_usesDefaultValue(value: boolean): boolean; + get_usesDefaultValue(): boolean; + set_usesDefaultValue(value: boolean): boolean; } - export module Navigation { + export namespace Navigation { export enum NavigationLinkType { root, friendlyUrl, @@ -8823,30 +8741,30 @@ declare namespace SP { } export class NavigationTermSetItem extends ClientObject { - public get_id(): Guid; + get_id(): Guid; - public get_isReadOnly(): boolean; + get_isReadOnly(): boolean; - public get_linkType(): NavigationLinkType; - public set_linkType(value: NavigationLinkType): NavigationLinkType; + get_linkType(): NavigationLinkType; + set_linkType(value: NavigationLinkType): NavigationLinkType; - public get_targetUrlForChildTerms(): CustomizableString; + get_targetUrlForChildTerms(): CustomizableString; - public get_catalogTargetUrlForChildTerms(): CustomizableString; + get_catalogTargetUrlForChildTerms(): CustomizableString; - public get_taxonomyName(): string; + get_taxonomyName(): string; - public get_title(): CustomizableString; + get_title(): CustomizableString; - public get_terms(): NavigationTermCollection; + get_terms(): NavigationTermCollection; - public get_view(): NavigationTermSetView; + get_view(): NavigationTermSetView; - public createTerm(termName: string, linkType: NavigationLinkType, termId: Guid): Taxonomy.Term; + createTerm(termName: string, linkType: NavigationLinkType, termId: Guid): Taxonomy.Term; - public getTaxonomyTermStore(): Taxonomy.TermStore; + getTaxonomyTermStore(): Taxonomy.TermStore; - public getResolvedDisplayUrl(browserQueryString: string): StringResult; + getResolvedDisplayUrl(browserQueryString: string): StringResult; } export class NavigationTermCollection extends ClientObjectCollection { @@ -8854,60 +8772,60 @@ declare namespace SP { } export class NavigationTerm extends NavigationTermSetItem { - public get_associatedFolderUrl(): string; - public set_associatedFolderUrl(value: string): string; + get_associatedFolderUrl(): string; + set_associatedFolderUrl(value: string): string; - public get_catalogTargetUrl(): CustomizableString; + get_catalogTargetUrl(): CustomizableString; - public get_categoryImageUrl(): string; - public set_categoryImageUrl(value: string): string; + get_categoryImageUrl(): string; + set_categoryImageUrl(value: string): string; - public get_excludedProviders(): NavigationTermProviderNameCollection; + get_excludedProviders(): NavigationTermProviderNameCollection; - public get_excludeFromCurrentNavigation(): boolean; - public set_excludeFromCurrentNavigation(value: boolean): boolean; + get_excludeFromCurrentNavigation(): boolean; + set_excludeFromCurrentNavigation(value: boolean): boolean; - public get_excludeFromGlobalNavigation(): boolean; - public set_excludeFromGlobalNavigation(value: boolean): boolean; + get_excludeFromGlobalNavigation(): boolean; + set_excludeFromGlobalNavigation(value: boolean): boolean; - public get_friendlyUrlSegment(): CustomizableString; + get_friendlyUrlSegment(): CustomizableString; - public get_hoverText(): string; - public set_hoverText(value: string): string; + get_hoverText(): string; + set_hoverText(value: string): string; - public get_isDeprecated(): boolean; - public get_isPinned(): boolean; - public get_isPinnedRoot(): boolean; + get_isDeprecated(): boolean; + get_isPinned(): boolean; + get_isPinnedRoot(): boolean; - public get_parent(): NavigationTerm; + get_parent(): NavigationTerm; - public get_simpleLinkUrl(): string; + get_simpleLinkUrl(): string; - public set_simpleLinkUrl(value: string): string; + set_simpleLinkUrl(value: string): string; - public get_targetUrl(): CustomizableString; + get_targetUrl(): CustomizableString; - public get_termSet(): NavigationTermSet; + get_termSet(): NavigationTermSet; - public getAsEditable(taxonomySession: Taxonomy.TaxonomySession): NavigationTerm; + getAsEditable(taxonomySession: Taxonomy.TaxonomySession): NavigationTerm; - public getWithNewView(newView: NavigationTermSetView): NavigationTerm; + getWithNewView(newView: NavigationTermSetView): NavigationTerm; - public getResolvedTargetUrl(browserQueryString: string, remainingUrlSegments: string[]): StringResult; + getResolvedTargetUrl(browserQueryString: string, remainingUrlSegments: string[]): StringResult; - public getResolvedTargetUrlWithoutQuery(): StringResult; + getResolvedTargetUrlWithoutQuery(): StringResult; - public getResolvedAssociatedFolderUrl(): StringResult; + getResolvedAssociatedFolderUrl(): StringResult; - public getWebRelativeFriendlyUrl(): StringResult; + getWebRelativeFriendlyUrl(): StringResult; - public getAllParentTerms(): NavigationTermCollection; + getAllParentTerms(): NavigationTermCollection; - public getTaxonomyTerm(): Taxonomy.Term; + getTaxonomyTerm(): Taxonomy.Term; - public move(newParent: NavigationTermSetItem): void; + move(newParent: NavigationTermSetItem): void; - public deleteObject(): void; + deleteObject(): void; static getAsResolvedByWeb(context: ClientContext, term: Taxonomy.Term, web: Web, siteMapProviderName: string): NavigationTerm; static getAsResolvedByView(context: ClientContext, term: Taxonomy.Term, view: NavigationTermSetView): NavigationTerm; @@ -8915,25 +8833,25 @@ declare namespace SP { export class NavigationTermSet extends NavigationTermSetItem { - public get_isNavigationTermSet(): boolean; - public set_isNavigationTermSet(value: boolean): boolean; + get_isNavigationTermSet(): boolean; + set_isNavigationTermSet(value: boolean): boolean; - public get_lcid(): number; + get_lcid(): number; - public get_loadedFromPersistedData(): boolean; + get_loadedFromPersistedData(): boolean; - public get_termGroupId(): Guid; - public get_termStoreId(): Guid; + get_termGroupId(): Guid; + get_termStoreId(): Guid; - public getAsEditable(taxonomySession: Taxonomy.TaxonomySession): NavigationTermSet; + getAsEditable(taxonomySession: Taxonomy.TaxonomySession): NavigationTermSet; - public getWithNewView(newView: NavigationTermSetView): NavigationTermSet; + getWithNewView(newView: NavigationTermSetView): NavigationTermSet; - public getTaxonomyTermSet(): Taxonomy.TermSet; + getTaxonomyTermSet(): Taxonomy.TermSet; - public getAllTerms(): NavigationTermCollection; + getAllTerms(): NavigationTermCollection; - public findTermForUrl(url: string): NavigationTerm; + findTermForUrl(url: string): NavigationTerm; static getAsResolvedByWeb(context: ClientContext, termSet: Taxonomy.TermSet, web: Web, siteMapProviderName: string): NavigationTermSet; static getAsResolvedByView(context: ClientContext, termSet: Taxonomy.TermSet, view: NavigationTermSetView): NavigationTermSet; @@ -8941,34 +8859,34 @@ declare namespace SP { export class NavigationTermProviderNameCollection extends ClientObjectCollection { - public Add(item: string): void; - public Clear(): void; - public Remove(item: string): BooleanResult; + Add(item: string): void; + Clear(): void; + Remove(item: string): BooleanResult; } export class NavigationTermSetView extends ClientObject { constructor(context: ClientContext, web: Web, siteMapProviderName: string); - public get_excludeDeprecatedTerms(): boolean; - public set_excludeDeprecatedTerms(value: boolean): boolean; + get_excludeDeprecatedTerms(): boolean; + set_excludeDeprecatedTerms(value: boolean): boolean; - public get_excludeTermsByPermissions(): boolean; - public set_excludeTermsByPermissions(value: boolean): boolean; + get_excludeTermsByPermissions(): boolean; + set_excludeTermsByPermissions(value: boolean): boolean; - public get_excludeTermsByProvider(): boolean; - public set_excludeTermsByProvider(value: boolean): boolean; + get_excludeTermsByProvider(): boolean; + set_excludeTermsByProvider(value: boolean): boolean; - public get_serverRelativeSiteUrl(): string; + get_serverRelativeSiteUrl(): string; - public get_serverRelativeWebUrl(): string; + get_serverRelativeWebUrl(): string; - public get_siteMapProviderName(): string; - public set_siteMapProviderName(value: string): string; + get_siteMapProviderName(): string; + set_siteMapProviderName(value: string): string; - public get_webId(): Guid; - public get_webTitle(): string; + get_webId(): Guid; + get_webTitle(): string; - public getCopy(): NavigationTermSetView; + getCopy(): NavigationTermSetView; static createEmptyInstance(context: ClientContext): NavigationTermSetView; } @@ -8986,29 +8904,29 @@ declare namespace SP { export class WebNavigationSettings extends ClientObject { constructor(context: ClientContext, web: Web); - public get_addNewPagesToNavigation(): boolean; - public set_addNewPagesToNavigation(value: boolean): boolean; + get_addNewPagesToNavigation(): boolean; + set_addNewPagesToNavigation(value: boolean): boolean; - public get_createFriendlyUrlsForNewPages(): boolean; - public set_createFriendlyUrlsForNewPages(value: boolean): boolean; + get_createFriendlyUrlsForNewPages(): boolean; + set_createFriendlyUrlsForNewPages(value: boolean): boolean; - public get_currentNavigation(): StandardNavigationSettings; - public get_globalNavigation(): StandardNavigationSettings; + get_currentNavigation(): StandardNavigationSettings; + get_globalNavigation(): StandardNavigationSettings; - public update(taxonomySession: Taxonomy.TaxonomySession): void; - public resetToDefaults(): void; + update(taxonomySession: Taxonomy.TaxonomySession): void; + resetToDefaults(): void; } export class StandardNavigationSettings extends ClientObject { - public get_termSetId(): Guid; - public set_termSetId(value: Guid): Guid; + get_termSetId(): Guid; + set_termSetId(value: Guid): Guid; - public get_termStoreId(): Guid; - public set_termStoreId(value: Guid): Guid; + get_termStoreId(): Guid; + set_termStoreId(value: Guid): Guid; - public get_source(): StandardNavigationSource; + get_source(): StandardNavigationSource; - public set_source(value: StandardNavigationSource): StandardNavigationSource; + set_source(value: StandardNavigationSource): StandardNavigationSource; } } @@ -9016,11 +8934,11 @@ declare namespace SP { } declare namespace SP { - export module CompliancePolicy { + export namespace CompliancePolicy { export enum SPContainerType { - site,//: 0, - web,//: 1, - list//: 2 + site, //: 0, + web, //: 1, + list //: 2 } export class SPContainerId extends ClientObject { @@ -9282,13 +9200,13 @@ declare namespace SP { } - export module Discovery { + export namespace Discovery { export enum ExportStatus { - notStarted,//: 0, - started,//: 1, - complete,//: 2, - failed//: 3 + notStarted, //: 0, + started, //: 1, + complete, //: 2, + failed //: 3 } export class Case extends ClientObject { @@ -9304,7 +9222,7 @@ declare namespace SP { } } - export module InformationPolicy { + export namespace InformationPolicy { export class ProjectPolicy extends SP.ClientObject { constructor(context: ClientRuntimeContext, objectPath: ObjectPath); get_description(): string; @@ -9341,30 +9259,30 @@ declare class SPClientAutoFill { Footer: number; Separator: number; Loading: number; - } + }; static KeyProperty: string; //= 'AutoFillKey'; - static DisplayTextProperty: string;// = 'AutoFillDisplayText'; + static DisplayTextProperty: string; //= 'AutoFillDisplayText'; static SubDisplayTextProperty: string; //= 'AutoFillSubDisplayText'; static TitleTextProperty: string; //= 'AutoFillTitleText'; - static MenuOptionTypeProperty: string;//= 'AutoFillMenuOptionType'; + static MenuOptionTypeProperty: string; //= 'AutoFillMenuOptionType'; static GetAutoFillObjFromInput(elmText: HTMLInputElement): SPClientAutoFill; static GetAutoFillObjFromContainer(elmChild: HTMLElement): SPClientAutoFill; static GetAutoFillMenuItemFromOption(elmChild: HTMLElement): HTMLElement; constructor(elmTextId: string, elmContainerId: string, fnPopulateAutoFill: (targetElement: HTMLInputElement) => void); - public TextElementId: string; - public AutoFillContainerId: string; - public AutoFillMenuId: string; - public VisibleItemCount: number; - public CurrentFocusOption: number; - public AutoFillMinTextLength: number; - public AutoFillTimeout: number; - public AutoFillCallbackTimeoutID: string; - public FuncOnAutoFillClose: (elmTextId: string, ojData: ISPClientAutoFillData) => void; - public FuncPopulateAutoFill: (targetElement: HTMLElement) => void; - public AllOptionData: { [key: string]: ISPClientAutoFillData }; + TextElementId: string; + AutoFillContainerId: string; + AutoFillMenuId: string; + VisibleItemCount: number; + CurrentFocusOption: number; + AutoFillMinTextLength: number; + AutoFillTimeout: number; + AutoFillCallbackTimeoutID: string; + FuncOnAutoFillClose: (elmTextId: string, ojData: ISPClientAutoFillData) => void; + FuncPopulateAutoFill: (targetElement: HTMLElement) => void; + AllOptionData: { [key: string]: ISPClientAutoFillData }; PopulateAutoFill(jsonObjSuggestions: ISPClientAutoFillData[], fnOnAutoFillCloseFuncName: (elmTextId: string, objData: ISPClientAutoFillData) => void): void; IsAutoFillOpen(): boolean; @@ -9377,6 +9295,7 @@ declare class SPClientAutoFill { UpdateAutoFillPosition(): void; } +// tslint:disable-next-line: interface-name interface ISPClientAutoFillData { AutoFillKey?: any; AutoFillDisplayText?: string; @@ -9418,101 +9337,102 @@ declare class SPClientPeoplePicker { static CreateSPPrincipalType(acctStr: string): number; - public TopLevelElementId: string; // '', - public EditorElementId: string; //'', - public AutoFillElementId: string; //'', - public ResolvedListElementId: string; //'', - public InitialHelpTextElementId: string; //'', - public WaitImageId: string; //'', - public HiddenInputId: string; //'', - public AllowEmpty: boolean; //true, - public ForceClaims: boolean; //false, - public AutoFillEnabled: boolean; //true, - public AllowMultipleUsers: boolean; //false, - public OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - public OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - public OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - public UrlZone: SP.UrlZone; //null, - public AllUrlZones: boolean; //false, - public SharePointGroupID: number; //0, - public AllowEmailAddresses: boolean; //false, - public PPMRU: SPClientPeoplePickerMRU; - public UseLocalSuggestionCache: boolean; //true, - public CurrentQueryStr: string; //'', - public LatestSearchQueryStr: string; // '', - public InitialSuggestions: ISPClientPeoplePickerEntity[]; - public CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; - public CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - public VisibleSuggestions: number; //5, - public PrincipalAccountType: string; //'', - public PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - public EnabledClaimProviders: string; //'', - public SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, - public ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, - public MaximumEntitySuggestions: number; //30, - public EditorWidthSet: boolean; //false, - public QueryScriptInit: boolean; //false, - public AutoFillControl: SPClientAutoFill; //null, - public TotalUserCount: number; //0, - public UnresolvedUserCount: number; //0, - public UserQueryDict: { [index: string]: SP.StringResult }; - public ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; - public HasInputError: boolean; //false, - public HasServerError: boolean; //false, - public ShowUserPresence: boolean; //true, - public TerminatingCharacter: string; //';', - public UnresolvedUserElmIdToReplace: string; //'', - public WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', - public GetAllUserInfo(): ISPClientPeoplePickerEntity[]; + TopLevelElementId: string; // '', + EditorElementId: string; //'', + AutoFillElementId: string; //'', + ResolvedListElementId: string; //'', + InitialHelpTextElementId: string; //'', + WaitImageId: string; //'', + HiddenInputId: string; //'', + AllowEmpty: boolean; //true, + ForceClaims: boolean; //false, + AutoFillEnabled: boolean; //true, + AllowMultipleUsers: boolean; //false, + OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; + OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; + OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; + UrlZone: SP.UrlZone; //null, + AllUrlZones: boolean; //false, + SharePointGroupID: number; //0, + AllowEmailAddresses: boolean; //false, + PPMRU: SPClientPeoplePickerMRU; + UseLocalSuggestionCache: boolean; //true, + CurrentQueryStr: string; //'', + LatestSearchQueryStr: string; // '', + InitialSuggestions: ISPClientPeoplePickerEntity[]; + CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; + CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; + VisibleSuggestions: number; //5, + PrincipalAccountType: string; //'', + PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; + EnabledClaimProviders: string; //'', + SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, + ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, + MaximumEntitySuggestions: number; //30, + EditorWidthSet: boolean; //false, + QueryScriptInit: boolean; //false, + AutoFillControl: SPClientAutoFill; //null, + TotalUserCount: number; //0, + UnresolvedUserCount: number; //0, + UserQueryDict: { [index: string]: SP.StringResult }; + ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; + HasInputError: boolean; //false, + HasServerError: boolean; //false, + ShowUserPresence: boolean; //true, + TerminatingCharacter: string; //';', + UnresolvedUserElmIdToReplace: string; //'', + WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', + GetAllUserInfo(): ISPClientPeoplePickerEntity[]; - public SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void - public AddUserKeys(userKeys: string, bSearch: boolean): void; - public BatchAddUserKeysOperation(allKeys: string[], numProcessed: number): void; - public ResolveAllUsers(fnContinuation: () => void): void; - public ExecutePickerQuery(queryIds: string, onSuccess: (queryId: string, result: SP.StringResult) => void, onFailure: (queryId: string, result: SP.StringResult) => void, fnContinuation: () => void): void; - public AddUnresolvedUserFromEditor(bRunQuery?: boolean): void; - public AddUnresolvedUser(unresolvedUserObj: ISPClientPeoplePickerEntity, bRunQuery?: boolean): void; - public UpdateUnresolvedUser(results: SP.StringResult, user: ISPClientPeoplePickerEntity): void; - public AddPickerSearchQuery(queryStr: string): string; - public AddPickerResolveQuery(queryStr: string): string; - public GetPeoplePickerQueryParameters(): SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters; - public AddProcessedUser(userObject: ISPClientPeoplePickerEntity, fResolved?: boolean): string; - public DeleteProcessedUser(elmToRemove: HTMLElement): void; - public OnControlValueChanged(): void; - public OnControlResolvedUserChanged(): void; - public EnsureAutoFillControl(): void; - public ShowAutoFill(resultsTable: ISPClientAutoFillData[]): void; - public FocusAutoFill(): void; - public BlurAutoFill(): void; - public IsAutoFillOpen(): boolean; - public EnsureEditorWidth(): void; - public SetFocusOnEditorEnd(): void; - public ToggleWaitImageDisplay(bShowImage?: boolean): void; - public SaveAllUserKeysToHiddenInput(): void; - public GetCurrentEditorValue(): string; - public GetControlValueAsJSObject(): ISPClientPeoplePickerEntity[]; - public GetAllUserKeys(): string; - public GetControlValueAsText(): string; - public IsEmpty(): boolean; - public IterateEachProcessedUser(fnCallback: (index: number, user: SPClientPeoplePickerProcessedUser) => void): void; - public HasResolvedUsers(): boolean; - public Validate(): void; - public ValidateCurrentState(): void - public GetUnresolvedEntityErrorMessage(): string; - public ShowErrorMessage(msg: string): void; - public ClearServerError(): void; - public SetServerError(): void; - public OnControlValidate(): void; - public SetEnabledState(bEnabled: boolean): void; - public DisplayLocalSuggestions(): void; - public CompileLocalSuggestions(input: string): void; - public PlanningGlobalSearch(): boolean; - public AddLoadingSuggestionMenuOption(): void; - public ShowingLocalSuggestions(): boolean; - public ShouldUsePPMRU(): boolean; - public AddResolvedUserToLocalCache(resolvedEntity: ISPClientPeoplePickerEntity, resolveText: string): void; + SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void + AddUserKeys(userKeys: string, bSearch: boolean): void; + BatchAddUserKeysOperation(allKeys: string[], numProcessed: number): void; + ResolveAllUsers(fnContinuation: () => void): void; + ExecutePickerQuery(queryIds: string, onSuccess: (queryId: string, result: SP.StringResult) => void, onFailure: (queryId: string, result: SP.StringResult) => void, fnContinuation: () => void): void; + AddUnresolvedUserFromEditor(bRunQuery?: boolean): void; + AddUnresolvedUser(unresolvedUserObj: ISPClientPeoplePickerEntity, bRunQuery?: boolean): void; + UpdateUnresolvedUser(results: SP.StringResult, user: ISPClientPeoplePickerEntity): void; + AddPickerSearchQuery(queryStr: string): string; + AddPickerResolveQuery(queryStr: string): string; + GetPeoplePickerQueryParameters(): SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters; + AddProcessedUser(userObject: ISPClientPeoplePickerEntity, fResolved?: boolean): string; + DeleteProcessedUser(elmToRemove: HTMLElement): void; + OnControlValueChanged(): void; + OnControlResolvedUserChanged(): void; + EnsureAutoFillControl(): void; + ShowAutoFill(resultsTable: ISPClientAutoFillData[]): void; + FocusAutoFill(): void; + BlurAutoFill(): void; + IsAutoFillOpen(): boolean; + EnsureEditorWidth(): void; + SetFocusOnEditorEnd(): void; + ToggleWaitImageDisplay(bShowImage?: boolean): void; + SaveAllUserKeysToHiddenInput(): void; + GetCurrentEditorValue(): string; + GetControlValueAsJSObject(): ISPClientPeoplePickerEntity[]; + GetAllUserKeys(): string; + GetControlValueAsText(): string; + IsEmpty(): boolean; + IterateEachProcessedUser(fnCallback: (index: number, user: SPClientPeoplePickerProcessedUser) => void): void; + HasResolvedUsers(): boolean; + Validate(): void; + ValidateCurrentState(): void + GetUnresolvedEntityErrorMessage(): string; + ShowErrorMessage(msg: string): void; + ClearServerError(): void; + SetServerError(): void; + OnControlValidate(): void; + SetEnabledState(bEnabled: boolean): void; + DisplayLocalSuggestions(): void; + CompileLocalSuggestions(input: string): void; + PlanningGlobalSearch(): boolean; + AddLoadingSuggestionMenuOption(): void; + ShowingLocalSuggestions(): boolean; + ShouldUsePPMRU(): boolean; + AddResolvedUserToLocalCache(resolvedEntity: ISPClientPeoplePickerEntity, resolveText: string): void; } +// tslint:disable-next-line: interface-name interface ISPClientPeoplePickerSchema { TopLevelElementId?: string; EditorElementId?: string; @@ -9562,16 +9482,17 @@ interface ISPClientPeoplePickerSchema { } declare class SPClientPeoplePickerMRU { - static PPMRUVersion: number;// = 1; - static MaxPPMRUItems: number;// = 200; - static PPMRUDomLocalStoreKey: string;// = "ClientPeoplePickerMRU"; + static PPMRUVersion: number; //= 1; + static MaxPPMRUItems: number; //= 200; + static PPMRUDomLocalStoreKey: string; //= "ClientPeoplePickerMRU"; static GetSPClientPeoplePickerMRU(): SPClientPeoplePickerMRU; - GetItems(strKey: string): Object[]; - SetItem(strSearchTerm: string, objEntity: Object): void; + GetItems(strKey: string): { Key: string, [name: string]: any }; + SetItem(strSearchTerm: string, objEntity: T): void; ResetCache(): void; } +// tslint:disable-next-line: interface-name interface ISPClientPeoplePickerEntity { Key?: string; Description?: string; @@ -9592,23 +9513,23 @@ interface ISPClientPeoplePickerEntity { } declare class SPClientPeoplePickerProcessedUser { - UserContainerElementId: string;// '', - DisplayElementId: string;// '', - PresenceElementId: string;// '', - DeleteUserElementId: string;// '', - SID: string;// '', - DisplayName: string;// '', - SIPAddress: string;// '', - UserInfo: ISPClientPeoplePickerEntity;// null, - ResolvedUser: boolean;// true, - Suggestions: ISPClientAutoFillData[];// null, - ErrorDescription: string;// '', - ResolveText: string;// '', - public UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; - public UpdateSuggestions(entity: ISPClientPeoplePickerEntity): void; - public BuildUserHTML(): string; - public UpdateUserMaxWidth(): void; - public ResolvedAsUnverifiedEmail(): string; + UserContainerElementId: string; //'', + DisplayElementId: string; //'', + PresenceElementId: string; //'', + DeleteUserElementId: string; //'', + SID: string; //'', + DisplayName: string; //'', + SIPAddress: string; //'', + UserInfo: ISPClientPeoplePickerEntity; //null, + ResolvedUser: boolean; //true, + Suggestions: ISPClientAutoFillData[]; //null, + ErrorDescription: string; //'', + ResolveText: string; //'', + UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; + UpdateSuggestions(entity: ISPClientPeoplePickerEntity): void; + BuildUserHTML(): string; + UpdateUserMaxWidth(): void; + ResolvedAsUnverifiedEmail(): string; static BuildUserPresenceHtml(elmId: string, strSip: string, bResolved?: boolean): string; static GetUserContainerElement(elmChild: HTMLElement): HTMLElement; @@ -9619,9 +9540,9 @@ declare class SPClientPeoplePickerProcessedUser { } declare namespace Microsoft { - export module Office { - export module Server { - export module ReputationModel { + export namespace Office { + export namespace Server { + export namespace ReputationModel { export class Reputation { constructor(); static setLike(context: SP.ClientContext, listId: string, itemId: number, like: boolean): void; @@ -9636,10 +9557,10 @@ declare namespace Microsoft { declare namespace Define { export function loadScript(url: string, successCallback: () => void, errCallback: () => void): void; /** Loads script from _layouts/15/[req].js */ - export function require(req: string, callback: Function): void; + export function require(req: string, callback: (arg: any[]) => void): void; /** Loads script from _layouts/15/[req].js */ - export function require(req: string[], callback: Function): void; - export function define(name: string, deps: string[], def: Function): void; + export function require(req: string[], callback: (...args: any[]) => void): void; + export function define(name: string, deps: string[], def: (...args: any[]) => any): void; } /** Available only in SharePoint Online*/ @@ -9695,7 +9616,7 @@ declare namespace DOM { export function GetEventSrcElement(evt: Event): HTMLElement; export function GetInnerText(el: HTMLElement): string; export function PreventDefaultNavigation(evt: Event): void; - export function SetEvent(eventName: string, eventFunc: Function, el: HTMLElement): void; + export function SetEvent(eventName: string, eventFunc: (eventName: string, fnContent: (evt: Event) => void, window?: Window) => void, el: HTMLElement): void; } /** Available only in SharePoint Online*/ @@ -9712,7 +9633,7 @@ declare namespace Encoding { /** Available only in SharePoint Online*/ declare namespace IE8Support { export function arrayIndexOf(array: T[], item: T, startIdx?: number): number; - export function attachDOMContentLoaded(handler: Function): void; + export function attachDOMContentLoaded(handler: () => void): void; export function getComputedStyle(domObj: HTMLElement, camelStyleName: string, dashStyleName: string): string; export function stopPropagation(evt: Event): void; } @@ -9747,10 +9668,10 @@ declare namespace Nav { export function goToDiscussion(url: string): void; export function onClickHook(evt: Event, topElm: HTMLElement): void; export function pageUrlValidation(url: string, alertString: string): string; - export function parseHash(hash: string): Object; + export function parseHash(hash: string): { [name: string]: string }; export function navigate(url: string): void; export function removeMDSQueryParametersFromUrl(url: string): string; - export function urlFromHashBag(hashObject: Object): string; + export function urlFromHashBag(hashObject: { [name: string]: string }): string; export function wantsNewTab(evt: Event): boolean; } @@ -9760,19 +9681,19 @@ declare namespace URI_Encoding { export function escapeUrlForCallback(str: string): string; } -interface IListItem { +interface ListItem { ID: number; ContentTypeId: string; } /** Available only in SharePoint Online*/ declare namespace ListModule { - export module Util { - export function createViewEditUrl(renderCtx: SPClientTemplates.RenderContext, listItem: IListItem, useEditFormUrl?: boolean, appendSource?: boolean): string; - export function createItemPropertiesTitle(renderCtx: SPClientTemplates.RenderContext, listItem: IListItem): string; + export namespace Util { + export function createViewEditUrl(renderCtx: SPClientTemplates.RenderContext, listItem: ListItem, useEditFormUrl?: boolean, appendSource?: boolean): string; + export function createItemPropertiesTitle(renderCtx: SPClientTemplates.RenderContext, listItem: ListItem): string; export function clearSelectedItemsDict(context: any): void; export function ctxInitItemState(context: any): void; - export function getAttributeFromItemTable(itemTableParam: HTMLElement, strAttributeName: string, strAttributeOldName: string): string + export function getAttributeFromItemTable(itemTableParam: HTMLElement, strAttributeName: string, strAttributeOldName: string): string; export function getSelectedItemsDict(context: any): any; export function removeOnlyPagingArgs(url: string): string; export function removePagingArgs(url: string): string; @@ -9783,13 +9704,13 @@ declare namespace ListModule { /** Available only in SharePoint Online*/ declare namespace SPThemeUtils { export function ApplyCurrentTheme(): void; - export function WithCurrentTheme(resultCallback: Function): void; + export function WithCurrentTheme(resultCallback: (themesCache: any) => void): void; export function UseClientSideTheming(): boolean; export function Suspend(): void; } declare namespace SP { - export module JsGrid { + export namespace JsGrid { export enum TextDirection { Default, //0, @@ -9863,13 +9784,13 @@ declare namespace SP { None //0 } - export module RowHeaderStyleId { + export namespace RowHeaderStyleId { export var Transfer: string; //'Transfer', export var Conflict: string; //'Conflict' } - export module RowHeaderAutoStyleId { + export namespace RowHeaderAutoStyleId { export var Dirty: string; //'Dirty', export var Error: string; //'Error', export var NewRow: string; //'NewRow' @@ -9898,7 +9819,7 @@ declare namespace SP { PropBoth //4 } - export module UserAction { + export namespace UserAction { export var UserEdit: string; //'User Edit':string; export var DeleteRecord: string; //'Delete Record':string; export var InsertRecord: string; //'Insert Record':string; @@ -9914,6 +9835,7 @@ declare namespace SP { ReadOnlyDisabled, //1 } + // tslint:disable-next-line: interface-name export interface IValue { data?: any; localized?: string; @@ -9974,14 +9896,14 @@ declare namespace SP { /** Switches the currently selected cell into edit mode: displays edit control and sets focus into it. Returns true if success. */ TryBeginEdit(): boolean; - FinalizeEditing(fnContinue: Function, fnError: Function): void; + FinalizeEditing(fnContinue: () => void, fnError: () => void): void; /** Get diff tracker object that tracks changes to the grid data. */ GetDiffTracker(): SP.JsGrid.Internal.DiffTracker; /** Moves focus to the JsGrid control */ Focus(): void; /** Try saving the new record row (aka entry row) if it was edited. */ - TryCommitFirstEntryRecords(fnCommitComplete: { (): void }): void; + TryCommitFirstEntryRecords(fnCommitComplete: () => void): void; /** Removes all new record rows (aka entry rows), including unsaved and even empty ones. The latter seems to be a bug, as I haven't found any easy way to restore the empty entry row. */ ClearUncommitedEntryRecords(): void; @@ -10036,7 +9958,7 @@ declare namespace SP { ToggleExpandCollapse(recordKey: number): void; /** Attach event handler to a particular event type */ - AttachEvent(eventType: JsGrid.EventType, fnOnEvent: { (args: IEventArgs): void }): void; + AttachEvent(eventType: JsGrid.EventType, fnOnEvent: (args: IEventArgs) => void): void; /** Detach a previously set event handler */ DetachEvent(eventType: JsGrid.EventType, fnOnEvent: any): void; @@ -10138,11 +10060,11 @@ declare namespace SP { If minId is specified, method searches for an error with first id which is greater than minId. Scrolls to the Returns the id of the found record. If there aren't any errors, that satisfy the conditions, method does nothing and returns null. */ - ScrollToAndExpandNextError(minId?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }): any; + ScrollToAndExpandNextError(minId?: number, fnFilter?: (recordKey: number, fieldKey: string, id: number) => boolean): any; /** Same as ScrollToAndExpandNextError, but searches within the specified record. recordKey should be not null, otherwise you'll get an exception. bDontExpand controls whether the error tooltip will be shown (if bDontExpand=true, tooltip will not be shown). */ - ScrollToAndExpandNextErrorOnRecord(minId?: number, recordKey?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }, bDontExpand?: boolean): any; + ScrollToAndExpandNextErrorOnRecord(minId?: number, recordKey?: number, fnFilter?: (recordKey: number, fieldKey: string, id: number) => boolean, bDontExpand?: boolean): any; GetFocusedItem(): any; SendKeyDownEvent(eventInfo: Sys.UI.DomEvent): any; @@ -10192,6 +10114,7 @@ declare namespace SP { GetSpCsrRenderCtx(): any; } + // tslint:disable-next-line: interface-name export interface IChangeKey { Reserve(): void; Release(): void; @@ -10277,11 +10200,11 @@ declare namespace SP { } export class RowHeaderState { - constructor(id: string, img: SP.JsGrid.Image, priority: SP.JsGrid.RowHeaderStatePriorities, tooltip: string, fnOnClick: { (eventInfo: Sys.UI.DomEvent, recordKey: number): void }); + constructor(id: string, img: SP.JsGrid.Image, priority: SP.JsGrid.RowHeaderStatePriorities, tooltip: string, fnOnClick: (eventInfo: Sys.UI.DomEvent, recordKey: number) => void); GetId(): string; GetImg(): SP.JsGrid.Image; GetPriority(): SP.JsGrid.RowHeaderStatePriorities; - GetOnClick(): { (eventInfo: Sys.UI.DomEvent, recordKey: number): void }; + GetOnClick(): (eventInfo: Sys.UI.DomEvent, recordKey: number) => void; GetTooltip(): string; toString(): string; } @@ -10298,11 +10221,11 @@ declare namespace SP { bIsAnimated: boolean; /** Renders the image with specified alternative text and on-click handler. If bHideTooltip == false, then alternative text is also shown as the tooltip (title attribute). */ - Render(altText: string, clickFn: { (eventInfo: Sys.UI.DomEvent): void }, bHideTooltip: boolean): HTMLElement; + Render(altText: string, clickFn: (eventInfo: Sys.UI.DomEvent) => void, bHideTooltip: boolean): HTMLElement; } - + // tslint:disable-next-line: interface-name no-empty-interface export interface IEventArgs { } - export module EventArgs { + export namespace EventArgs { export class OnEntryRecordAdded implements IEventArgs { constructor(recordKey: number); recordKey: number; @@ -10389,7 +10312,7 @@ declare namespace SP { constructor(origRecKey: string, recordKey: number, changeKey: JsGrid.IChangeKey); originalRecordKey: number; recordKey: number; - changeKey: JsGrid.IChangeKey + changeKey: JsGrid.IChangeKey; } export class SingleCellClick implements IEventArgs { constructor(eventInfo: Sys.UI.DomEvent, recordKey: number, fieldKey: string); @@ -10399,11 +10322,11 @@ declare namespace SP { } export class PendingChangeKeyInitiallyComplete implements IEventArgs { constructor(changeKey: JsGrid.IChangeKey); - changeKey: JsGrid.IChangeKey + changeKey: JsGrid.IChangeKey; } export class VacateChange implements IEventArgs { constructor(changeKey: JsGrid.IChangeKey); - changeKey: JsGrid.IChangeKey + changeKey: JsGrid.IChangeKey; } export class GridErrorStateChanged implements IEventArgs { constructor(bAnyErrors: boolean); @@ -10432,16 +10355,16 @@ declare namespace SP { } export class OnBeginRedoDataUpdateChange implements IEventArgs { constructor(changeKey: JsGrid.IChangeKey); - changeKey: JsGrid.IChangeKey + changeKey: JsGrid.IChangeKey; } export class OnBeginUndoDataUpdateChange implements IEventArgs { constructor(changeKey: JsGrid.IChangeKey); - changeKey: JsGrid.IChangeKey + changeKey: JsGrid.IChangeKey; } } - export module JsGridControl { + export namespace JsGridControl { export class Parameters { tableCache: SP.JsGrid.TableCache; name: any; // TODO @@ -10488,16 +10411,16 @@ declare namespace SP { rowViewParams: RowViewParameters; } export class PivotedGridParameters { - //this.dateRange = null; - // this.ganttBarStyles = null; - // this.ganttZoomLevel = 3; - // this.fnRenderGanttRow = null; - // this.fnGetGanttBarDate = null; - // this.fnGetGanttBarStyleIds = null; - // this.fnGetPredecessors = null; - // this.workDayStart = _spRegionalSettings.workDayStart; - // this.workDayEnd = _spRegionalSettings.workDayEnd; - // this.fieldKeyRedrawFilter = null; + //this.dateRange = null; + // this.ganttBarStyles = null; + // this.ganttZoomLevel = 3; + // this.fnRenderGanttRow = null; + // this.fnGetGanttBarDate = null; + // this.fnGetGanttBarStyleIds = null; + // this.fnGetPredecessors = null; + // this.workDayStart = _spRegionalSettings.workDayStart; + // this.workDayEnd = _spRegionalSettings.workDayEnd; + // this.fieldKeyRedrawFilter = null; } export class GanttParameters { @@ -10533,6 +10456,7 @@ declare namespace SP { // todo } + // tslint:disable-next-line: interface-name export interface IStyleManager { gridPaneStyle: IStyleType.GridPane; columnHeaderStyleCollection: { @@ -10575,9 +10499,9 @@ declare namespace SP { UpdateDefaultCellStyleFromCss(styleObject: IStyleType.Cell, cssClass: string): void; UpdateGroupStylesFromCss(styleObject: IStyleType.Cell, prefix: string): void; } - + // tslint:disable-next-line: no-empty-interface interface-name export interface IStyleType { } - export module IStyleType { + export namespace IStyleType { export interface Splitter extends IStyleType { outerBorderColor: any; leftInnerBorderColor: any; @@ -10688,19 +10612,19 @@ declare namespace SP { Widget: IStyleType.Widget; }; - static SetRTL: { (rtlObject: any): void; }; - static MakeJsGridStyleManager: { (): IStyleManager }; - static CreateStyleFromCss: { (styleType: IStyleType, cssStyleName: string, optExistingStyle?: any, optClassId?: any): any; }; - static CreateStyle: { (styleType: IStyleType, styleProps: any): any; }; - static MergeCellStyles: { (majorStyle: any, minorStyle: any): any; }; - static ApplyCellStyle: { (td: HTMLTableCellElement, style: any): void; }; - static ApplyRowHeaderStyle: { (domObj: HTMLElement, style: any, fnGetHeaderSibling: Function): void; }; - static ApplyCornerHeaderBorderStyle: { (domObj: HTMLElement, colStyle: any, rowStyle: any): void; }; - static ApplyHeaderInnerBorderStyle: { (domObj: HTMLElement, bIsRowHeader: any, headerObject: any): void }; - static ApplyColumnContextMenuStyle: { (domObj: HTMLElement, style: any): void }; - static ApplySplitterStyle: { (domObj: HTMLElement, style: any): void }; - static MakeBorderString: { (width: number, style: string, color: string): string }; - static GetCellStyleDefaultBackgroundColor: { (): string }; + static SetRTL: (rtlObject: any) => void; + static MakeJsGridStyleManager: () => IStyleManager; + static CreateStyleFromCss: (styleType: IStyleType, cssStyleName: string, optExistingStyle?: any, optClassId?: any) => any; + static CreateStyle: (styleType: IStyleType, styleProps: any) => any; + static MergeCellStyles: (majorStyle: any, minorStyle: any) => any; + static ApplyCellStyle: (td: HTMLTableCellElement, style: any) => void; + static ApplyRowHeaderStyle: (domObj: HTMLElement, style: any, fnGetHeaderSibling: (elem: HTMLElement, previousElem: boolean) => void) => void; + static ApplyCornerHeaderBorderStyle: (domObj: HTMLElement, colStyle: any, rowStyle: any) => void; + static ApplyHeaderInnerBorderStyle: (domObj: HTMLElement, bIsRowHeader: any, headerObject: any) => void; + static ApplyColumnContextMenuStyle: (domObj: HTMLElement, style: any) => void; + static ApplySplitterStyle: (domObj: HTMLElement, style: any) => void; + static MakeBorderString: (width: number, style: string, color: string) => string; + static GetCellStyleDefaultBackgroundColor: () => string; } @@ -10750,32 +10674,33 @@ declare namespace SP { /** false by default */ isFooter: boolean; /** determine whether the cells in this column should be clickable */ - fnShouldLinkSingleValue: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): boolean }; + fnShouldLinkSingleValue: (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any) => boolean; /** if a particular cell is determined as clickable by fnShouldLinkSingleValue, this function will be called when the cell is clicked */ - fnSingleValueClicked: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): void }; + fnSingleValueClicked: (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any) => void; /** this is used when you need to make some of the cells in the column readonly, but at the same time keep others editable */ - fnGetCellEditMode: { (record: IRecord, fieldKey: string): JsGrid.EditMode }; + fnGetCellEditMode: (record: IRecord, fieldKey: string) => JsGrid.EditMode; /** this function should return name of the display control for the given cell in the column the name should be previously associated with the display control via SP.JsGrid.PropertyType.Utils.RegisterDisplayControl method */ - fnGetDisplayControlName: { (record: IRecord, fieldKey: string): string }; + fnGetDisplayControlName: (record: IRecord, fieldKey: string) => string; /** this function should return name of the edit control for the given cell in the column the name should be previously associated with the edit control via SP.JsGrid.PropertyType.Utils.RegisterEditControl method */ - fnGetEditControlName: { (record: IRecord, fieldKey: string): string }; + fnGetEditControlName: (record: IRecord, fieldKey: string) => string; /** set widget control names for a particular cell widgets are basically in-cell buttons with associated popup controls, e.g. date selector or address book button standard widget ids are defined in the SP.JsGrid.WidgetControl.Type enumeration it is also possible to create your own widgets usually this function is not used, and instead, widget control names are determined via PropertyType */ - fnGetWidgetControlNames: { (record: IRecord, fieldKey: string): string[] }; + fnGetWidgetControlNames: (record: IRecord, fieldKey: string) => string[]; /** this function should return id of the style for the given cell in the column styles and their ids are registered for a JsGridControl via jsGridParams.styleManager.RegisterCellStyle method */ - fnGetCellStyleId: { (record: IRecord, fieldKey: string, dataValue: any): string }; + fnGetCellStyleId: (record: IRecord, fieldKey: string, dataValue: any) => string; /** set custom tooltip for the given cell in the column. by default, localized value is displayed as the tooltip */ - fnGetSingleValueTooltip: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): string }; + fnGetSingleValueTooltip: (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any) => string; } + // tslint:disable-next-line: interface-name export interface IRecord { /** True if this is an entry row */ bIsNewRow: boolean; @@ -10812,6 +10737,7 @@ declare namespace SP { MakeRecord(dataPropMap: any, localizedPropMap: any, bKeepRawData: boolean): IRecord; } + // tslint:disable-next-line: interface-name export interface IPropertyBase { HasLocalizedValue(): boolean; HasDataValue(): boolean; @@ -10847,6 +10773,7 @@ declare namespace SP { GetIsMultiValue(): boolean; } + // tslint:disable-next-line: interface-name export interface IEditActorGridContext { jsGridObj: JsGridControl; parentNode: HTMLElement; @@ -10854,19 +10781,22 @@ declare namespace SP { RTL: any; emptyValue: any; bLightFocus: boolean; - OnKeyDown: { (domEvent: Sys.UI.DomEvent): void; }; + OnKeyDown: (domEvent: Sys.UI.DomEvent) => void; } + // tslint:disable-next-line: interface-name export interface IEditControlGridContext extends IEditActorGridContext { OnActivateActor(): void; OnDeactivateActor(): void; } + // tslint:disable-next-line: interface-name export interface IPropertyType { ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; } + // tslint:disable-next-line: interface-name export interface ILookupPropertyType extends IPropertyType { GetItems(fnCallback: any): void; DataToLocalized(dataValue: any): string; @@ -10877,6 +10807,7 @@ declare namespace SP { GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; } + // tslint:disable-next-line: interface-name export interface IMultiValuePropertyType extends IPropertyType { bMultiValue: boolean; separator: string; @@ -10899,18 +10830,17 @@ declare namespace SP { /** Register a custom property type, where display and edit controls, and also widgets, are derived from the specified parent property type. */ static RegisterNewDerivedCustomPropType(propType: IPropertyType, baseTypeName: string): void; } - - export module PropertyType { + export namespace PropertyType { export class String implements IPropertyType { constructor(); ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; toString(): string; } export class LookupTable implements ILookupPropertyType { constructor(items: any[], id: string, bLimitToList: boolean); ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; GetItems(fnCallback: any): void; DataToLocalized(dataValue: any): string; LocalizedToData(localized: string): any; @@ -10923,7 +10853,7 @@ declare namespace SP { export class CheckBoxBoolean implements IPropertyType { constructor(); ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; DataToLocalized(dataValue: any): string; GetBool(dataValue: any): boolean; toString(): string; @@ -10931,14 +10861,14 @@ declare namespace SP { export class DropDownBoolean implements IPropertyType { constructor(); ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; DataToLocalized(dataValue: any): string; GetBool(dataValue: any): boolean; toString(): string; } export class MultiValuePropType implements IMultiValuePropertyType { ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; bMultiValue: boolean; separator: string; singleValuePropType: string; @@ -10949,7 +10879,7 @@ declare namespace SP { } export class HyperLink implements IPropertyType { ID: string; - BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }) => void, fnError: any): void; bHyperlink: boolean; DataToLocalized(dataValue: any): string; GetAddress(dataValue: any): string; @@ -10962,13 +10892,13 @@ declare namespace SP { export class Utils { static RegisterDisplayControl(name: string, singleton: any, requiredFunctionNames: string[]): void; static RegisterEditControl(name: string, factory: (gridContext: IEditControlGridContext, gridTextInputElement: HTMLElement) => IEditControl, requiredFunctionNames: string[]): void; - static RegisterWidgetControl(name: string, factory: { (ddContext: any): IPropertyType; }, requiredFunctionNames: string[]): void; + static RegisterWidgetControl(name: string, factory: (ddContext: any) => IPropertyType, requiredFunctionNames: string[]): void; static UpdateDisplayControlForPropType(propTypeName: string, displayControlType: string): void; } } - export module WidgetControl { + export namespace WidgetControl { export class Type { static Demo: string; static Date: string; @@ -10977,9 +10907,9 @@ declare namespace SP { } } - export module Internal { + export namespace Internal { export class DiffTracker { - constructor(objBag: any, fnGetChange: Function); + constructor(objBag: any, fnGetChange: (version: any, keys: any[], synchronized: boolean, includeInvalidPropUpdates: boolean) => any); ExternalAPI: { AnyChanges(): boolean; ChangeKeySliceInfo(): any; @@ -11004,6 +10934,7 @@ declare namespace SP { } } + // tslint:disable-next-line: interface-name export interface IEditActorCellContext { propType: IPropertyType; originalValue: IValue; @@ -11015,6 +10946,7 @@ declare namespace SP { SetCurrentValue(value: any): void; } + // tslint:disable-next-line: interface-name export interface IEditControlCellContext extends IEditActorCellContext { cellWidth: number; cellHeight: number; @@ -11027,10 +10959,11 @@ declare namespace SP { } - export module EditControl { + export namespace EditControl { } + // tslint:disable-next-line: interface-name export interface IEditControl { SupportedWriteMode?: SP.JsGrid.EditActorWriteType; SupportedReadMode?: SP.JsGrid.EditActorReadType; @@ -11052,14 +10985,15 @@ declare namespace SP { export class StaticDataSource { - constructor(jsGridData: IGridData, optFnGetPropType?: Function); - AddColumn(gridField: SP.JsGrid.GridField, values: IValue[]):void; - RemoveColumn(fieldKey: string):void; + constructor(jsGridData: IGridData, optFnGetPropType?: (recordKey: string, key: string, dataPropMap: { [name: string]: any }) => any); + AddColumn(gridField: SP.JsGrid.GridField, values: IValue[]): void; + RemoveColumn(fieldKey: string): void; InitJsGridParams(optGridParams?: JsGridControl.Parameters): JsGridControl.Parameters; } + // tslint:disable-next-line: interface-name export interface IGridData { - MetaData: IGridMetadata + MetaData: IGridMetadata; Fields: IFieldInfo[]; Columns: IColumnInfo[]; @@ -11088,6 +11022,7 @@ declare namespace SP { ViewDepKeys?: any[]; } + // tslint:disable-next-line: interface-name export interface IColumnInfo { /** Column title */ name: string; @@ -11117,6 +11052,7 @@ declare namespace SP { isFooter?: boolean; } + // tslint:disable-next-line: interface-name export interface IGridMetadata { KeyColumnName: string; IsGanttEnabled?: boolean; @@ -11130,6 +11066,7 @@ declare namespace SP { } + // tslint:disable-next-line: interface-name export interface IFieldInfo { fieldKey: string; propertyTypeId: string; @@ -11143,6 +11080,7 @@ declare namespace SP { } + // tslint:disable-next-line: interface-name export interface ILookupTableInfo { id: string; showImage?: boolean; @@ -11150,6 +11088,8 @@ declare namespace SP { limitToList?: boolean; lookup: ILookupInfo[]; } + + // tslint:disable-next-line: interface-name export interface ILookupInfo { localString: string; value: number; @@ -11158,9 +11098,10 @@ declare namespace SP { } - export module Utilities { + export namespace Utilities { export class Set { constructor(items?: { [item: string]: number }); + // tslint:disable-next-line: unified-signatures constructor(items?: { [item: number]: number }); /** Returns true if the set is empty */ IsEmpty(): boolean; @@ -11206,7 +11147,7 @@ declare namespace SP { export class GanttControl { static WaitForGanttCreation(callack: (control: GanttControl) => void): void; static Instances: GanttControl[]; - static FnGanttCreationCallback: { (control: GanttControl): void }[]; + static FnGanttCreationCallback: Array<(control: GanttControl) => void>; get_Columns(): SP.JsGrid.ColumnInfo[]; } @@ -11215,49 +11156,43 @@ declare namespace SP { // ------- Srch namespace ------- -declare namespace Srch -{ - export enum EventType - { - none, - queryReady, - queryIssuing, - batchQueryIssuing, - resultReady, - batchResultReady, - queryStateChanged, - resultRendered, - preLoad, - load, +declare namespace Srch { + export enum EventType { + none, + queryReady, + queryIssuing, + batchQueryIssuing, + resultReady, + batchResultReady, + queryStateChanged, + resultRendered, + preLoad, + load, postLoad } - export enum MessageLevel - { - information, - warning, - error + export enum MessageLevel { + information, + warning, + error } - export enum UserActionType - { - search, - pageNext, - pagePrev, - refine, - sort, + export enum UserActionType { + search, + pageNext, + pagePrev, + refine, + sort, filterLanguage } - export enum DateTimeKind - { - unspecified, - utc, + export enum DateTimeKind { + unspecified, + utc, local } - export class ClientControl extends Sys.UI.Control - { + export class ClientControl extends Sys.UI.Control { constructor(elem: Element); /** toggles visibility of children controls of the messageContainer */ @@ -11277,7 +11212,7 @@ declare namespace Srch /** If set to true, control will load scripts defined by the serverTemplateScriptsToLoad field after control load. True by default. */ set_delayLoadTemplateScripts(value: boolean): boolean; get_states(): any; - set_states(value: any): any; + set_states(value: any): any; get_messages(): any[]; set_messages(value: any[]): any[]; get_showDataErrors(): boolean; @@ -11294,7 +11229,7 @@ declare namespace Srch scriptApplication_PreLoad(sender: any, e: any): void; scriptApplication_Load(sender: any, e: any): void; scriptApplication_PostLoad(sender: any, e: any): void; - loadServerTemplateScripts():void; + loadServerTemplateScripts(): void; serverTemplateScriptsToLoad: any[]; serverTemplateScriptsCallback(): void; loadRenderTemplateScripts(scriptReferences: any, success: any, failure: any, timeout: any, loadStandAloneCustomScripts: any): boolean; @@ -11309,8 +11244,7 @@ declare namespace Srch clickHandler(e: Event): any; } - export class DataProvider extends ClientControl - { + export class DataProvider extends ClientControl { constructor(elem: Element); get_currentQueryState(): any; get_sourceID(): string; @@ -11440,8 +11374,7 @@ declare namespace Srch getSortName(): string; } - export class DisplayControl extends ClientControl - { + export class DisplayControl extends ClientControl { get_queryGroupName(): string; set_queryGroupName(value: string): string; get_dataProvider(): DataProvider; @@ -11473,8 +11406,7 @@ declare namespace Srch render(): void; } - export class Refinement extends DisplayControl - { + export class Refinement extends DisplayControl { static createRefinementTextbox(name: string): Element; static submitMultiRefinement(name: string, control: Refinement, useContains: boolean, useKQL: boolean): void; static ensureUserSpecifiedRefinerValueHasWhiteSpaceQuotes(inputText: string): string; @@ -11485,7 +11417,7 @@ declare namespace Srch /** Save expanded state of the specified filter to cookie */ static setExpanded(filterName: string, value: string): void; static multiRefinerSpecifyOtherFilterValue(refinerName: string, clientControl: Refinement, useContains: boolean, useKQL: boolean): void; - + constructor(elem: Element); get_selectedRefinementControls(): RefinementControl[]; @@ -11494,7 +11426,7 @@ declare namespace Srch set_useManagedNavigationRefiners(value: boolean): boolean; get_emptyRefinementMessageId(): string; set_emptyRefinementMessageId(value: string): string; - + scriptApplication_PreLoad(sender: any, e: any): void; render(): void; addRefinementFilter(filterName: string, filterToken: any): void; @@ -11521,8 +11453,7 @@ declare namespace Srch updateRefinementControls(newControls: RefinementControl[]): void; } - export class RefinementControl - { + export class RefinementControl { constructor(propertyName: string, spec: string, renderTemplateId: string); propertyName: string; @@ -11537,8 +11468,7 @@ declare namespace Srch deepHits: number; } - export class Result extends DisplayControl - { + export class Result extends DisplayControl { static parsePropertyMappingWithSlotDisplayNames(mappings: any): { [key: string]: any }; static parsePropertyMappingsString(mappings: any): { [key: string]: any }; static getSelectedPropertiesFromMappingDictionary(propMappings: any): any[]; @@ -11611,8 +11541,7 @@ declare namespace Srch } /** Represents the search box control */ - export class SearchBox extends ClientControl - { + export class SearchBox extends ClientControl { constructor(elem: Element); /** Returns the current search term */ @@ -11625,7 +11554,7 @@ declare namespace Srch get_queryGroupNames(): string[]; set_queryGroupNames(value: any): string[]; - + /** Gets the results page address, e.g. '~site/_layouts/15/osssearchresults.aspx?u={contexturl}' */ get_resultsPageAddress(): string; /** Sets the results page address, e.g. '~site/_layouts/15/osssearchresults.aspx?u={contexturl}' @@ -11633,19 +11562,19 @@ declare namespace Srch * e.g. specified site are returned. Omit this parameter if you want to search everywhere. */ set_resultsPageAddress(value: string): string; - + get_showAdvancedLink(): boolean; set_showAdvancedLink(value: boolean): boolean; - + get_showQuerySuggestions(): boolean; set_showQuerySuggestions(value: boolean): boolean; - + get_showNavigation(): boolean; set_showNavigation(value: boolean): boolean; - + get_showPeopleNameSuggestions(): boolean; set_showPeopleNameSuggestions(value: boolean): boolean; - + /** Gets the interval in milliseconds, if user is idle during this interval, suggestions retrieval will be initiated. * Default value is 250. */ @@ -11654,57 +11583,57 @@ declare namespace Srch * Default value is 250. */ set_querySuggestionCompletionInterval(value: number): number; - + /** Gets minimum length of the search term for suggestions to be retrieved. Default is 2 letters. */ get_querySuggestionMinimumPrefixLength(): number; /** Sets minimum length of the search term for suggestions to be retrieved. Default is 2 letters. */ set_querySuggestionMinimumPrefixLength(value: number): number; - + /** Gets number of suggestions to display. Default is 5. */ get_querySuggestionCount(): number; /** Sets number of suggestions to display. Default is 5. */ set_querySuggestionCount(value: number): number; - + get_personalResultCount(): number; set_personalResultCount(value: number): number; - + get_advancedSearchPageAddress(): string; set_advancedSearchPageAddress(value: string): string; - + get_showPreferencesLink(): boolean; set_showPreferencesLink(value: boolean): boolean; - + get_serverInitialRender(): boolean; set_serverInitialRender(value: boolean): boolean; - + get_setFocusOnPageLoad(): boolean; set_setFocusOnPageLoad(value: boolean): boolean; - + get_allowEmptySearch(): boolean; set_allowEmptySearch(value: boolean): boolean; - + get_updatePageTitle(): boolean; set_updatePageTitle(value: boolean): boolean; - + get_pageTitlePrefix(): string; set_pageTitlePrefix(value: string): string; - + /** Gets the search input placeholder text */ get_currentPrompt(): string; /** Sets the search input placeholder text */ set_currentPrompt(value: string): string; - + get_initialPrompt(): string; set_initialPrompt(value: string): string; - + /** Gets the css class/classes of the placeholder text. Default is 'ms-srch-sb-prompt ms-helperText' */ get_promptCssClass(): string; /** Sets the css class/classes of the placeholder text. Default is 'ms-srch-sb-prompt ms-helperText' */ set_promptCssClass(value: string): string; - + get_tryInplaceQuery(): boolean; set_tryInplaceQuery(value: boolean): boolean; - + /** Gets the id of the search box input element */ get_searchBoxInputId(): string; /** Sets the id of the search box input element */ @@ -11712,40 +11641,40 @@ declare namespace Srch get_searchBoxContainerId(): string; set_searchBoxContainerId(value: string): string; - + get_navigationButtonId(): string; set_navigationButtonId(value: string): string; - + get_suggestionsListId(): string; set_suggestionsListId(value: string): string; - + get_navigationListId(): string; set_navigationListId(value: string): string; - + get_searchBoxInputElement(): Element; - + get_searchBoxProgressClass(): string; set_searchBoxProgressClass(value: string): string; - + get_searchBoxContainerElement(): Element; - + get_searchBoxLinkId(): string; set_searchBoxLinkId(value: string): string; - + get_searchBoxLinkElement(): Element; - + get_navigationNodes(): any; set_navigationNodes(value: any): any; - + get_msBeforeShowingProgress(): number; set_msBeforeShowingProgress(value: number): number; - + get_maintainQueryState(): boolean; set_maintainQueryState(value: boolean): boolean; - + get_querySuggestionsSourceID(): string; set_querySuggestionsSourceID(value: string): string; - + scriptApplication_PreLoad(sender: any, e: any): void; scriptApplication_PostLoad(sender: any, e: any): void; serverTemplateScriptsCallback(): any; @@ -11778,19 +11707,20 @@ declare namespace Srch } - export class U - { + type RenderFunction = (ctx: any) => string; + + export class U { /** Returns true if the value parameter is null or empty string */ static e(value: string): boolean; /** Returns true if the value parameter is empty string */ - static w(value: any): boolean; + static w(value: any): boolean; /** Returns true if the value parameter is null or undefined */ static n(value: any): boolean; /** Returns true if current page is in edit mode */ static isPageInEditMode(): boolean; /** Returns true if current page is displayed in the Minimal Download Strategy (MDS) mode */ static isPageInMdsMode(): boolean; - + static isPagePartialLoad(): boolean; /** Returns true if the current page uses right-to-left mode (RTL) */ static isRTL(): boolean; @@ -11838,9 +11768,9 @@ declare namespace Srch static traceFormatted(c: Srch.ClientControl, method: string, format: string, ...values: string[]): void; /** Same as $addHandler with safety checks */ - static addHandler(element: Element, eventName: string, handler: Function): void; + static addHandler(element: Element, eventName: string, handler: (instance: any, eventArgs: any) => void): void; /** Same as $removeHandler with safety checks */ - static removeHandler(element: Element, eventName: string, handler: Function): void + static removeHandler(element: Element, eventName: string, handler: (instance: any, eventArgs: any) => void): void /** Returns true if the specified element is a descendant of the container element */ static isDescendant(element: Element, container: Element): boolean; @@ -11864,7 +11794,7 @@ declare namespace Srch static ensureAllowedProtocol(value: string): string; /** Indicates whether the specified protocol is allowed. */ static isProtocolAllowed(value: string, allowRelativeUrl: boolean): boolean; - + /** Returns true if the URL is a relative URL */ static isUrlRelative(url: string): boolean; /** Returns true if the URL is a server-relative URL (i.e. starts with '/') */ @@ -11874,7 +11804,7 @@ declare namespace Srch static logClick(e: any, clickType: any): void; static fillKeywordQuery(query: any, dp: any): void; - + /** Parses username out from SharePoint user field value */ static getUsernameFromAuthorField(authorField: string): string; /** Parses user display name out from SharePoint user field value */ @@ -11908,14 +11838,14 @@ declare namespace Srch /** Copies the specified string to clipboard, if possible */ static copyLink(link: string): void; - + /** Registers display template function in the system. * @param name Identifier of the template. Usually template is registered twice: by URL and by name. * @param template The display template. It can be either string, or function, that gets the CSR context object and returns HTML string */ - static registerRenderTemplateByName(name: string, templateFunction: string | { (ctx: any): string }): void; + static registerRenderTemplateByName(name: string, templateFunction: string | RenderFunction): void; /** Returns display template registered (can be either string or function) */ - static getRenderTemplateByName(name: string, renderCtx: any): string | { (ctx: any): string }; + static getRenderTemplateByName(name: string, renderCtx: any): string | RenderFunction; static addRenderContextCallback(renderCtx: any, callbackType: any, callbackFunction: any, enforceUnique: any, templateFunction: any): void; static setItemRenderWrapper(renderCtx: any, itemRenderWrapperFunction: any, templateFunction: any): any; @@ -11924,7 +11854,7 @@ declare namespace Srch static getTemplateUrlFromFunctionOrRenderCtx(templateFunctionOrRenderCtx: any): string; static createErrorObjectWithExecContext(messageText: any, operationName: any, templateFuncOrRenderCtx: any): any; /** Returns the CSR template that was previously registered using 'registerRenderTemplateByName' based on CSR template level */ - static resolveRenderTemplate(renderCtx: any, component: ClientControl, level: 'Item' | 'Group' | 'View' | 'Body'): string | { (ctx: any): string }; + static resolveRenderTemplate(renderCtx: any, component: ClientControl, level: 'Item' | 'Group' | 'View' | 'Body'): string | RenderFunction; /** Returns formatted time string from seconds string, which contains a number that represents amount of seconds passed since 00:00:00 today */ static getFormattedTimeFromSeconds(secondsStr: string): string; @@ -11945,14 +11875,14 @@ declare namespace Srch static getFolderIconUrl(): string; /** Returns URL of the appropriate file image based on the file type identifier (see getFriendlyNameForFileExtension) */ static getIconUrlByFileExtension(item: string, defaultIconPath?: string): string; - + /** Returns string that contains safe call to HP.Show, passing over the itemId, hpContainerId and templateUrl parameters, and supplying true for wide parameter. */ static getShowHoverPanelCallbackWide(itemId: string, hpContainerId: string, templateUrl: string): string; /** Returns string that contains safe call to HP.Show, passing over the itemId, hpContainerId and templateUrl parameters, and supplying false for wide parameter. */ static getShowHoverPanelCallback(itemId: string, hpContainerId: string, templateUrl: string): string; /** Returns string that contains safe call to HP.Hide */ static getHideHoverPanelCallback(): string; - + static getHighlightedProperty(key: string, result: any, property: string): any; static processHHXML(pre: string): string; static createXMLDocument(xml: string): XMLDocument; @@ -11970,7 +11900,7 @@ declare namespace Srch static isFirstRankedBlock(resultTable: Microsoft.SharePoint.Client.Search.Query.ResultTable): boolean; static isIntentTable(resultTable: Microsoft.SharePoint.Client.Search.Query.ResultTable): boolean; static createBehavior(id: string, type: any, properties: any, targetElementId: string): any; - + /** Uses SPAnimation to animate an element */ static animate(element: Element, animationID: any, finishFunc: any): void; static hideElement(element: Element): void; @@ -11979,11 +11909,11 @@ declare namespace Srch static resetElement(element: Element): void; static shouldAnimate(dp: any): boolean; static animateResults(result: Result, userAction: any): void; - + static loadScripts(scriptReferences: string[], success: any, failure: any, timeout: number): void; static appendScriptsToLoad(scripts: string[], script: string): void; static registerLoadedScripts(scripts: string[]): void; - + /** Returns HTML for collapsible refiner title */ static collapsibleRefinerTitle(propertyName: string, idPrefix: string, title: string, iconClass: string, customOnClick: string): string; /** Returns true if current page is osssearchresults.aspx */ @@ -11992,7 +11922,7 @@ declare namespace Srch static replaceUrlTokens(url: string): string; /** Adds ctag parameter to the URL and replaces URL tokens */ static urlTokenExpansion(jsLink: string): string; - + static includeCSS(templateLink: string, relativeLink: string): void; static includeScript(templateLink: string, scriptLink: string): void; static includeLanguageScript(templateLink: string, scriptLink: string): void; @@ -12001,9 +11931,9 @@ declare namespace Srch /** Retrieves localized string with the specified id */ static loadResource(id: string): string; /** Retrieves localized string with the specified id */ - static loadResourceForTemplate(id: string, templateFunc: {(ctx: any): string}): string; + static loadResourceForTemplate(id: string, templateFunc: (ctx: any) => string): string; /** Registers in system resources defined by the dictionary object */ - static registerResourceDictionary(locale:string, dict: {[key: string]: string}): void; + static registerResourceDictionary(locale: string, dict: { [key: string]: string }): void; static restorePath(el: Element, originalText: string, selectText: string): void; static selectPath(text: string, el: Element): void; @@ -12035,9 +11965,8 @@ declare namespace Srch static contentFixedWidthLength: number; } - export module U { - export class PropNames - { + export namespace U { + export class PropNames { static renderTemplates: 'RenderTemplates'; static renderTemplateId: 'RenderTemplateId'; static tableType: 'TableType'; @@ -12055,8 +11984,7 @@ declare namespace Srch static isFirstRankedBlock: 'IsFirstRankedResultBlock'; } - export class Ids - { + export class Ids { static group: '_group'; static groupTitle: '_groupTitle'; static groupLink: '_groupLink'; @@ -12079,23 +12007,20 @@ declare namespace Srch static postInfo: '_postInfo'; } - export class LoadScriptsState - { + export class LoadScriptsState { scriptsToLoad: any; progress: number; timeoutHandle: any; } - export enum LoadScriptsProgress - { + export enum LoadScriptsProgress { loading, success, failure } } - export class ScriptApplicationManager - { + export class ScriptApplicationManager { static get_current(): ScriptApplicationManager; static get_clientRuntimeContext(): SP.ClientRuntimeContext; /** Returns server-relative link to _layouts/EditUserPref.aspx */ @@ -12112,23 +12037,23 @@ declare namespace Srch get_pagePath(): string; /** Adds handler for the preload event */ - add_preLoad(handlerFunction: Function): void; + add_preLoad(handlerFunction: (instance: any, eventArgs: any) => void): void; /** Removes handler for the preload event */ - remove_preLoad(handlerFunction: Function): void; + remove_preLoad(handlerFunction: (instance: any, eventArgs: any) => void): void; /** Raises the preload event */ raisePreLoadEvent(): void; /** Adds handler for the load event */ - add_load(handlerFunction: Function): void; + add_load(handlerFunction: (instance: any, eventArgs: any) => void): void; /** Removes handler for the load event */ - remove_load(handlerFunction: Function): void; + remove_load(handlerFunction: (instance: any, eventArgs: any) => void): void; /** Raises the load event */ raiseLoadEvent(): void; /** Adds handler for the postload event */ - add_postLoad(handlerFunction: Function): void; + add_postLoad(handlerFunction: (instance: any, eventArgs: any) => void): void; /** Removes handler for the postload event */ - remove_postLoad(handlerFunction: Function): void; + remove_postLoad(handlerFunction: (instance: any, eventArgs: any) => void): void; /** Raises the postload event */ raisePostLoadEvent(): void; @@ -12139,7 +12064,7 @@ declare namespace Srch * After registration the controls will be correctly processed in the page search context. */ registerClientControl(clientControl: DisplayControl | DataProvider | SearchBox): void; - + /** Puts specified hash-key address into the current page location. * @param url The hash-key, e.g. '#k=test' */ @@ -12149,8 +12074,7 @@ declare namespace Srch get_searchSessionID(): void; } - export class Res - { + export class Res { static sb_ResultsPageTitle: string; static sb_EmptyQueryWarning: string; static sb_InvalidResultPageURL: string; @@ -12783,7 +12707,7 @@ declare namespace Srch static rs_PartialResultWarning_Line1: string; static rs_PartialResultWarning_Line2: string; static rs_HasParseExceptionWarning_Line1: string; - static rs_HasParseExceptionWarning_Line2: string; + static rs_HasParseExceptionWarning_Line2: string; } } @@ -12832,7 +12756,7 @@ declare function $includeScript(templateLink: string, relativeLink: string): voi declare function $includeCSS(templateLink: string, scriptLink: string): void; declare function $includeLanguageScript(templateLink: string, scriptLink: string): any; /** Registers in system resources defined by the dictionary object (alias for Srch.U.registerResourceDictionary) */ -declare function $registerResourceDictionary(locale:string, dict: {[key: string]: string}): void; +declare function $registerResourceDictionary(locale: string, dict: { [key: string]: string }): void; /** Retrieves localized string with the specified id */ declare function $resource(id: string): string; /** (calls Srch.U.setItemRenderWrapper) */ diff --git a/sharepoint/sharepoint-tests.ts b/sharepoint/sharepoint-tests.ts index 6155a0b096..9d75197d89 100644 --- a/sharepoint/sharepoint-tests.ts +++ b/sharepoint/sharepoint-tests.ts @@ -6,14 +6,14 @@ import * as ng from 'angular'; //code from http://sptypescript.codeplex.com/ //BasicTasksJSOM.ts // Website tasks -function retrieveWebsite(resultpanel:HTMLElement) { +function retrieveWebsite(resultpanel: HTMLElement) { var clientContext = SP.ClientContext.get_current(); var oWebsite = clientContext.get_web(); clientContext.load(oWebsite); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -24,7 +24,6 @@ function retrieveWebsite(resultpanel:HTMLElement) { resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); } } - function retrieveWebsiteProps(resultpanel: HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -32,7 +31,7 @@ function retrieveWebsiteProps(resultpanel: HTMLElement) { clientContext.load(oWebsite, "Description", "Created"); - clientContext.executeQueryAsync(successHandler,errorHandler); + clientContext.executeQueryAsync(successHandler, errorHandler); function successHandler() { resultpanel.innerHTML = "Description: " + oWebsite.get_description() + @@ -55,8 +54,8 @@ function writeWebsiteProps(resultpanel: HTMLElement) { clientContext.load(oWebsite, "Description"); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); @@ -79,8 +78,8 @@ function readAllProps(resultpanel: HTMLElement) { clientContext.load(collList); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -112,8 +111,8 @@ function readSpecificProps(resultpanel: HTMLElement) { clientContext.load(collList, "Include(Title, Id)"); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -144,14 +143,13 @@ function readColl(resultpanel: HTMLElement) { var listInfoCollection = clientContext.loadQuery(collList, "Include(Title, Id)"); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { var listInfo = ""; - for (var i = 0; i < listInfoCollection.length; i++) { - var oList = listInfoCollection[i]; + for (var oList of listInfoCollection) { listInfo += "Title: " + oList.get_title() + " ID: " + oList.get_id().toString() + "
"; } @@ -173,14 +171,13 @@ function readFilter(resultpanel: HTMLElement) { "Include(Title,Fields.Include(Title,InternalName))"); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { - for (var i = 0; i < listInfoArray.length; i++) { - var oList = listInfoArray[i]; + for (var oList of listInfoArray) { var collField = oList.get_fields(); var fieldEnumerator = collField.getEnumerator(); @@ -219,8 +216,8 @@ function createList(resultpanel: HTMLElement) { clientContext.load(oList); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -243,8 +240,8 @@ function updateList(resultpanel: HTMLElement) { clientContext.load(oList); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -268,7 +265,7 @@ function addField(resultpanel: HTMLElement) { SP.AddFieldOptions.defaultValue ); - var fieldNumber = clientContext.castTo(oField, SP.FieldNumber); + var fieldNumber = clientContext.castTo(oField, SP.FieldNumber) as SP.FieldNumber; fieldNumber.set_maximumValue(100); fieldNumber.set_minimumValue(35); fieldNumber.update(); @@ -276,8 +273,8 @@ function addField(resultpanel: HTMLElement) { clientContext.load(oField); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -298,8 +295,8 @@ function deleteList(resultpanel: HTMLElement) { oList.deleteObject(); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -325,8 +322,8 @@ function createFolder(resultpanel: HTMLElement) { clientContext.load(oListItem); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -343,14 +340,14 @@ function updateFolder(resultpanel: HTMLElement) { var oWebsite = clientContext.get_web(); var oList = oWebsite.get_lists().getByTitle("Shared Documents"); - var oListItem = oList.getItemById(1); + var oListItem = oList.getItemById(1); oListItem.set_item("FileLeafRef", "My updated folder"); oListItem.update(); clientContext.load(oListItem); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -363,7 +360,7 @@ function updateFolder(resultpanel: HTMLElement) { } function deleteFolder(resultpanel: HTMLElement) { - var clientContext = SP.ClientContext.get_current(); + var clientContext = SP.ClientContext.get_current(); var oWebsite = clientContext.get_web(); var oList = oWebsite.get_lists().getByTitle("Shared Documents"); @@ -371,8 +368,8 @@ function deleteFolder(resultpanel: HTMLElement) { oListItem.deleteObject(); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -399,8 +396,8 @@ function readItems(resultpanel: HTMLElement) { clientContext.load(collListItem); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -433,8 +430,8 @@ function readInclude(resultpanel: HTMLElement) { clientContext.load(collListItem, "Include(Id, DisplayName, HasUniqueRoleAssignments)"); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -444,8 +441,8 @@ function readInclude(resultpanel: HTMLElement) { while (listItemEnumerator.moveNext()) { var oListItem = listItemEnumerator.get_current(); listItemInfo += "ID: " + oListItem.get_id() + "
" + - "Display name: " + oListItem.get_displayName() + "
" + - "Unique role assignments: " + oListItem.get_hasUniqueRoleAssignments() + "
"; + "Display name: " + oListItem.get_displayName() + "
" + + "Unique role assignments: " + oListItem.get_hasUniqueRoleAssignments() + "
"; } resultpanel.innerHTML = listItemInfo; @@ -470,8 +467,8 @@ function createListItem(resultpanel: HTMLElement) { clientContext.load(oListItem); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -494,8 +491,8 @@ function updateListItem(resultpanel: HTMLElement) { clientContext.load(oListItem); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -516,8 +513,8 @@ function deleteListItem(resultpanel: HTMLElement) { oListItem.deleteObject(); clientContext.executeQueryAsync( - successHandler, - errorHandler + successHandler, + errorHandler ); function successHandler() { @@ -534,25 +531,21 @@ function deleteListItem(resultpanel: HTMLElement) { /** Lightweight client-side rendering template overrides.*/ namespace CSR { - export interface UpdatedValueCallback { - (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; - } + export type UpdatedValueCallback = (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm) => void; /** Creates new overrides. Call .register() at the end.*/ - export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { + export function override(listTemplateType?: number, baseViewId?: number | string): CSR { return new csr(listTemplateType, baseViewId) .onPreRender(hookFormContext) .onPostRender(fixCsrCustomLayout); - function hookFormContext(ctx: IFormRenderContexWithHook) { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - - for (var i = 0; i < ctx.ListSchema.Field.length; i++) { - var fieldSchemaInForm = ctx.ListSchema.Field[i]; + function hookFormContext(ctx: FormRenderContexWithHook) { + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + for (var fieldSchemaInForm of ctx.ListSchema.Field) { if (!ctx.FormContextHook) { - ctx.FormContextHook = {} + ctx.FormContextHook = {}; var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { @@ -568,11 +561,11 @@ namespace CSR { hookedContext.lastValue = value; var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; - for (var i = 0; i < updatedCallbacks.length; i++) { - updatedCallbacks[i](value, hookedContext.fieldSchema); + for (var updatedCallback of updatedCallbacks) { + updatedCallback(value, hookedContext.fieldSchema); } - } + }; } ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; } @@ -580,8 +573,8 @@ namespace CSR { } function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid - || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode === SPClientTemplates.ClientControlMode.View) { return; } @@ -604,8 +597,7 @@ namespace CSR { var old = ctx.CurrentItem; ctx.CurrentItem = ctx.ListData.Items[0]; var fields = ctx.ListSchema.Field; - for (var j = 0; j < fields.length; j++) { - var field = fields[j]; + for (var field of fields) { var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; var span = $get(pHolderId); if (span) { @@ -621,12 +613,12 @@ namespace CSR { } -//typescripttempltes.ts - declare var Strings:any; + //typescripttempltes.ts + declare var Strings: any; export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx as FormRenderContexWithHook; if (contextWithHook.FormContextHook && contextWithHook.FormContextHook[fieldName] && contextWithHook.FormContextHook[fieldName].getValue) { @@ -637,9 +629,9 @@ namespace CSR { } export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx as FormRenderContexWithHook; if (contextWithHook.FormContextHook && contextWithHook.FormContextHook[fieldName]) { return contextWithHook.FormContextHook[fieldName].fieldSchema; @@ -649,13 +641,13 @@ namespace CSR { } export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx as FormRenderContexWithHook; if (contextWithHook.FormContextHook) { var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); var callbacks = f.updatedValueCallbacks; - if (callbacks.indexOf(callback) == -1) { + if (callbacks.indexOf(callback) === -1) { callbacks.push(callback); if (f.lastValue) { callback(f.lastValue, f.fieldSchema); @@ -667,13 +659,13 @@ namespace CSR { } export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var contextWithHook = ctx; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx as FormRenderContexWithHook; if (contextWithHook.FormContextHook) { var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; var index = callbacks.indexOf(callback); - if (index != -1) { + if (index !== -1) { callbacks.splice(index, 1); } } @@ -683,7 +675,7 @@ namespace CSR { export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; //TODO: Handle different input types - return $get(id); + return $get(id) as HTMLInputElement; } export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { @@ -694,148 +686,148 @@ namespace CSR { } - class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { + class csr implements CSR, SPClientTemplates.TemplateOverridesOptions { - public Templates: SPClientTemplates.TemplateOverrides; - public OnPreRender: SPClientTemplates.RenderCallback[]; - public OnPostRender: SPClientTemplates.RenderCallback[]; + Templates: SPClientTemplates.TemplateOverrides; + OnPreRender: SPClientTemplates.RenderCallback[]; + OnPostRender: SPClientTemplates.RenderCallback[]; private IsRegistered: boolean; constructor(public ListTemplateType?: number, public BaseViewID?: any) { this.Templates = { Fields: {} }; - this.OnPreRender = [] ; + this.OnPreRender = []; this.OnPostRender = []; this.IsRegistered = false; } /* tier 1 methods */ - view(template: any): ICSR { + view(template: any): CSR { this.Templates.View = template; return this; } - item(template: any): ICSR { + item(template: any): CSR { this.Templates.Item = template; return this; } - header(template: any): ICSR { + header(template: any): CSR { this.Templates.Header = template; return this; } - body(template: any): ICSR { + body(template: any): CSR { this.Templates.Body = template; return this; } - footer(template: any): ICSR { + footer(template: any): CSR { this.Templates.Footer = template; return this; } - fieldView(fieldName: string, template: any): ICSR { + fieldView(fieldName: string, template: any): CSR { this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; this.Templates.Fields[fieldName].View = template; return this; } - fieldDisplay(fieldName: string, template: any): ICSR { + fieldDisplay(fieldName: string, template: any): CSR { this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; this.Templates.Fields[fieldName].DisplayForm = template; return this; } - fieldNew(fieldName: string, template: any): ICSR { + fieldNew(fieldName: string, template: any): CSR { this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; this.Templates.Fields[fieldName].NewForm = template; return this; } - fieldEdit(fieldName: string, template: any): ICSR { + fieldEdit(fieldName: string, template: any): CSR { this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; this.Templates.Fields[fieldName].EditForm = template; return this; } /* tier 2 methods */ - template(name: string, template: any): ICSR { + template(name: string, template: any): CSR { this.Templates[name] = template; return this; } - fieldTemplate(fieldName: string, name: string, template: any): ICSR { + fieldTemplate(fieldName: string, name: string, template: any): CSR { this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; this.Templates.Fields[fieldName][name] = template; return this; } /* common */ - onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { - for (var i = 0; i < callbacks.length; i++) { - this.OnPreRender.push(callbacks[i]); + onPreRender(...callbacks: Array<(ctx: SPClientTemplates.RenderContext) => void>): CSR { + for (var cb of callbacks) { + this.OnPreRender.push(cb); } return this; } - onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { - for (var i = 0; i < callbacks.length; i++) { - this.OnPostRender.push(callbacks[i]); + onPostRender(...callbacks: Array<(ctx: SPClientTemplates.RenderContext) => void>): CSR { + for (var cb of callbacks) { + this.OnPostRender.push(cb); } return this; } - onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + onPreRenderField(field: string, callback: (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext) => void): CSR { return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { - var ctxInView = ctx; + var ctxInView = ctx as SPClientTemplates.RenderContext_InView; //ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { - for (var i = 0; i < fields.length; i++) { - if (fields[i].Name === field) { - callback(fields[i], ctx); + for (var innerField of fields) { + if (innerField.Name === field) { + callback(innerField, ctx); } } } }); } - onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + onPostRenderField(field: string, callback: (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext) => void): CSR { return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { - var ctxInView = ctx; + var ctxInView = ctx as SPClientTemplates.RenderContext_InView; //ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { - for (var i = 0; i < fields.length; i++) { - if (fields[i].Name === field) { - callback(fields[i], ctx); + for (var innerField of fields) { + if (innerField.Name === field) { + callback(innerField, ctx); } } } }); } - makeReadOnly(fieldName: string): ICSR { + makeReadOnly(fieldName: string): CSR { return this .onPreRenderField(fieldName, (schema, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid - || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; - (schema).ReadOnlyField = true; - (schema).ReadOnly = "TRUE"; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode === SPClientTemplates.ClientControlMode.DisplayForm) return; + (schema as SPClientTemplates.FieldSchema_InForm).ReadOnlyField = true; + (schema as SPClientTemplates.FieldSchema_InView).ReadOnly = "TRUE"; - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - var ctxInView = ctx; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { //TODO: Disable editing in grid mode } } else { - var ctxInForm = ctx; - if (schema.Type != 'User' && schema.Type != 'UserMulti') { + var ctxInForm = ctx as SPClientTemplates.RenderContext_FieldInForm; + if (schema.Type !== 'User' && schema.Type !== 'UserMulti') { var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); ctxInForm.Templates.Fields[fieldName] = template; @@ -846,9 +838,9 @@ namespace CSR { }) .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - if (schema.Type == 'User' || schema.Type == 'UserMulti') { + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + if (schema.Type === 'User' || schema.Type === 'UserMulti') { SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; var retryCount = 10; @@ -858,7 +850,7 @@ namespace CSR { if (retryCount--) setTimeout(callback, 1); } else { pp.SetEnabledState(false); - pp.DeleteProcessedUser = function () { }; + pp.DeleteProcessedUser = function deleteProcessedUser() { /*dummy function*/}; } }; callback(); @@ -868,13 +860,13 @@ namespace CSR { }); } - makeHidden(fieldName: string): ICSR { + makeHidden(fieldName: string): CSR { return this.onPreRenderField(fieldName, (schema, ctx) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; - (schema).Hidden = true; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.Invalid) return; + (schema as SPClientTemplates.FieldSchema_InForm).Hidden = true; - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { - var ctxInView = ctx; + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { //TODO: Hide item in grid mode @@ -883,7 +875,7 @@ namespace CSR { } } else { - var ctxInForm = ctx; + var ctxInForm = ctx as SPClientTemplates.RenderContext_Form; var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; var placeholder = $get(pHolderId); @@ -891,7 +883,7 @@ namespace CSR { while (current.tagName.toUpperCase() !== "TR") { current = current.parentElement; } - var row = current; + var row = current as HTMLTableRowElement; row.style.display = 'none'; } @@ -899,7 +891,7 @@ namespace CSR { }); } - filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): CSR { return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) @@ -911,7 +903,10 @@ namespace CSR { var parseRegex = /\{[^\}]+\}/g; var dependencyExpressions: string[] = []; var result: RegExpExecArray; - while ((result = parseRegex.exec(camlFilter))) { + function nextResult() { + return result = parseRegex.exec(camlFilter); + } + while (nextResult()) { dependencyExpressions.push(stripBraces(result[0])); } var dependencyValues: { [expr: string]: string } = {}; @@ -928,7 +923,7 @@ namespace CSR { return ''; - var _schema = _myData.fieldSchema; + var _schema = _myData.fieldSchema as SPClientTemplates.FieldSchema_InForm_Lookup; var validators = new SPClientForms.ClientValidation.ValidatorSet(); validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); @@ -941,7 +936,7 @@ namespace CSR { var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; - var _noValueSelected = _selectedValue == 0; + var _noValueSelected = _selectedValue === 0; var _optionsLoaded = false; var pendingLoads = 0; @@ -950,11 +945,11 @@ namespace CSR { _myData.registerInitCallback(_myData.fieldName, InitLookupControl); - _myData.registerFocusCallback(_myData.fieldName, function () { + _myData.registerFocusCallback(_myData.fieldName, function focusCallback() { if (_dropdownElt != null) _dropdownElt.focus(); }); - _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + _myData.registerValidationErrorCallback(_myData.fieldName, function validationErrorCallback(errorResult) { SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); }); _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); @@ -963,7 +958,7 @@ namespace CSR { return BuildLookupDropdownControl(); function InitLookupControl() { - _dropdownElt = document.getElementById(_dropdownId); + _dropdownElt = document.getElementById(_dropdownId) as HTMLSelectElement; if (_dropdownElt != null) AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); @@ -994,7 +989,7 @@ namespace CSR { function GetCurrentLookupValue() { if (_dropdownElt == null) return ''; - return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + (_dropdownElt.options[_dropdownElt.selectedIndex] as any /* TODO remove `as any` */).text; + return _dropdownElt.value === '0' || _dropdownElt.value === '' ? '' : _dropdownElt.value + ';#' + (_dropdownElt.options[_dropdownElt.selectedIndex] as any /* TODO remove `as any` */).text; } function stripBraces(input: string): string { @@ -1005,7 +1000,7 @@ namespace CSR { var isLookupValue = !!listId; if (isLookupValue) { var lookup = SPClientTemplates.Utility.ParseLookupValue(value); - if (expressionParts.length == 1 && expressionParts[0] == 'Value') { + if (expressionParts.length === 1 && expressionParts[0] === 'Value') { value = lookup.LookupValue; expressionParts.shift(); } else { @@ -1013,7 +1008,7 @@ namespace CSR { } } - if (expressionParts.length == 0) { + if (expressionParts.length === 0) { dependencyValues[expr] = value; callback(); } else { @@ -1029,11 +1024,11 @@ namespace CSR { ctx.executeQueryAsync((o, e) => { var value = item.get_item(field.get_internalName()); - if (field.get_typeAsString() == 'Lookup') { - field = ctx.castTo(field, SP.FieldLookup); - var lookup = (value); + if (field.get_typeAsString() === 'Lookup') { + field = ctx.castTo(field, SP.FieldLookup) as SP.Field; + var lookup = (value as SP.FieldLookupValue); value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); - listId = (field).get_lookupList(); + listId = (field as SP.FieldLookup).get_lookupList(); } getDependencyValue(expr, value, listId, expressionParts, callback); @@ -1050,7 +1045,7 @@ namespace CSR { CSR.addUpdatedValueCallback(rCtx, field, (v, s) => { getDependencyValue(expr, v, - (s).LookupListId, + (s as SPClientTemplates.FieldSchema_InForm_Lookup).LookupListId, exprParts.slice(0), loadOptions); }); @@ -1076,7 +1071,7 @@ namespace CSR { }); //TODO: Handle ShowField attribure - if (predicate.substr(0, 5) == '' + @@ -1098,7 +1093,7 @@ namespace CSR { if (!_schema.Required) { var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); (_dropdownElt.options as any /* TODO remove `as any` */).add(defaultOpt); - selected = _selectedValue == 0; + selected = _selectedValue === 0; } var isEmptyList = true; @@ -1112,11 +1107,11 @@ namespace CSR { id = c.get_id(); text = c.get_item('Title'); } else { - var value = c.get_item(lookupField); + var value = c.get_item(lookupField) as SP.FieldLookupValue; id = value.get_lookupId(); text = value.get_lookupValue(); } - var isSelected = _selectedValue == id; + var isSelected = _selectedValue === id; if (isSelected) { selected = true; } @@ -1128,12 +1123,12 @@ namespace CSR { _optionsLoaded = true; if (!pendingLoads) { if (isFirstLoad) { - if (_selectedValue == 0 && !selected) { + if (_selectedValue === 0 && !selected) { _dropdownElt.selectedIndex = 0; OnLookupValueChanged(); } } else { - if (_selectedValue != 0 && !selected) { + if (_selectedValue !== 0 && !selected) { _dropdownElt.selectedIndex = 0; } OnLookupValueChanged(); @@ -1147,9 +1142,9 @@ namespace CSR { } - koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { + koEditField(fieldName: string, template: string, vm: KoFieldInForm, dependencyFields?: string[]): CSR { return this.fieldEdit(fieldName, koEditField_Edit) - .fieldNew(fieldName, koEditField_Edit); + .fieldNew(fieldName, koEditField_Edit); function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { @@ -1166,12 +1161,12 @@ namespace CSR { if (dependencyFields) { dependencyFields.forEach(dependencyField => { - if (!vm[dependencyField]) { - vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); - } - CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { - vm[dependencyField](v); - }); + if (!vm[dependencyField]) { + vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); + } + CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { + vm[dependencyField](v); + }); }); } @@ -1188,17 +1183,17 @@ namespace CSR { ko.applyBindings(vm, $get(elementId)); }); - return '
'+template+'
'; + return '
' + template + '
'; } } - computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): CSR { var dependentValues: { [field: string]: string } = {}; return this.onPostRenderField(targetField, (schema: SPClientTemplates.FieldSchema_InForm, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { - var targetControl = CSR.getControl(schema); + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) { + var targetControl = CSR.getControl(schema as SPClientTemplates.FieldSchema_InForm); sourceField.forEach((field) => { CSR.addUpdatedValueCallback(ctx, field, v => { dependentValues[field] = v; @@ -1211,7 +1206,7 @@ namespace CSR { }); } - setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { + setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): CSR { if (value || !ignoreNull) { return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { ctx.ListData.Items[0][fieldName] = value; @@ -1222,7 +1217,7 @@ namespace CSR { } - autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { + autofill(fieldName: string, init: (ctx: AutoFillFieldContext) => () => void): CSR { return this .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); @@ -1247,11 +1242,11 @@ namespace CSR { _myData.registerClientValidator(_myData.fieldName, validators); _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); - _myData.registerFocusCallback(_myData.fieldName, function () { + _myData.registerFocusCallback(_myData.fieldName, function focusCallback() { if (_textInputElt != null) _textInputElt.focus(); }); - _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + _myData.registerValidationErrorCallback(_myData.fieldName, function validationErrorCallback(errorResult) { SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); }); _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); @@ -1260,7 +1255,7 @@ namespace CSR { return buildAutoFillControl(); function initAutoFillControl() { - _textInputElt = document.getElementById(_textInputId); + _textInputElt = document.getElementById(_textInputId) as HTMLInputElement; SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); @@ -1302,20 +1297,20 @@ namespace CSR { } - seachLookup(fieldName: string): ICSR { - return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { + seachLookup(fieldName: string): CSR { + return this.autofill(fieldName, (ctx: AutoFillFieldContext) => { var _myData = ctx.fieldContext; - var _schema = _myData.fieldSchema; - if (_myData.fieldSchema.Type != 'Lookup') { + var _schema = _myData.fieldSchema as SPClientTemplates.FieldSchema_InForm_Lookup; + if (_myData.fieldSchema.Type !== 'Lookup') { return null; } var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); - var _noValueSelected = _selectedValue.LookupId == 0; + var _noValueSelected = _selectedValue.LookupId === 0; ctx.control.value = _selectedValue.LookupValue; $addHandler(ctx.control, "blur", _ => { - if (ctx.control.value == '') { + if (ctx.control.value === '') { _myData.fieldValue = ''; _myData.updateControlValue(fieldName, _myData.fieldValue); } @@ -1356,13 +1351,13 @@ namespace CSR { var rows = relevantResults.get_resultRows(); var items = []; - for (var i = 0; i < rows.length; i++) { - items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); + for (var row of rows) { + items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(row["ListItemId"], 10), row["Title"])); } items.push(AutoFillOptionBuilder.buildSeparatorItem()); - if (relevantResults.get_totalRows() == 0) + if (relevantResults.get_totalRows() === 0) items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); else items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); @@ -1375,7 +1370,7 @@ namespace CSR { console.log(args.get_message()); }); }); - } + }; function onSelectItem(targetInputId, item: ISPClientAutoFillData) { var targetElement = ctx.control; @@ -1389,16 +1384,16 @@ namespace CSR { }); } - lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): CSR { return this.onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { - if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm - || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) + if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode === SPClientTemplates.ClientControlMode.NewForm) var control = CSR.getControl(schema); if (control) { var weburl = _spPageContextInfo.webServerRelativeUrl; - if (weburl[weburl.length - 1] == '/') { + if (weburl[weburl.length - 1] === '/') { weburl = weburl.substring(0, weburl.length - 1); } var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' @@ -1476,56 +1471,48 @@ namespace CSR { } } - + type RenderContext = (ctx: SPClientTemplates.RenderContext) => T; /** Lightweight client-side rendering template overrides.*/ - export interface ICSR { + export interface CSR { /** Override rendering template. @param name Name of template to override. @param template New template. */ - template(name: string, template: string): ICSR; + template(name: string, template: string | RenderContext): CSR; /** Override rendering template. @param name Name of template to override. @param template New template. */ - template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; /** Override field rendering template. @param name Internal name of field to override. @param name Name of template to override. @param template New template. */ - fieldTemplate(field: string, name: string, template: string): ICSR; - - /** Override field rendering template. - @param name Internal name of field to override. - @param name Name of template to override. - @param template New template. - */ - fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + fieldTemplate(field: string, name: string, template: string | RenderContext): CSR; /** Sets pre-render callbacks. Callback called before rendering starts. @param callbacks pre-render callbacks. */ - onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + onPreRender(...callbacks: Array>): CSR; /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. @param callbacks post-render callbacks. */ - onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + onPostRender(...callbacks: Array>): CSR; /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. @param fieldName Internal name of the field. @param callbacks pre-render callbacks. */ - onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + onPreRenderField(field: string, callback: (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext) => void): CSR; /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. @param fieldName Internal name of the field. @param callbacks post-render callbacks. */ - onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + onPostRenderField(field: string, callback: (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext) => void): CSR; /** Registers overrides in client-side templating engine.*/ register(): void; @@ -1533,179 +1520,168 @@ namespace CSR { /** Override View rendering template. @param template New view template. */ - view(template: string): ICSR; + view(template: string): CSR; /** Override View rendering template. @param template New view template. */ - view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; - view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + // tslint:disable-next-line: unified-signatures + view(template: (ctx: SPClientTemplates.RenderContext_InView | SPClientTemplates.RenderContext_Form) => string): CSR; /** Override Item rendering template. @param template New item template. */ - item(template: string): ICSR; + item(template: string): CSR; /** Override Item rendering template. @param template New item template. */ - item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; - item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + // tslint:disable-next-line: unified-signatures + item(template: (ctx: SPClientTemplates.RenderContext_ItemInView | SPClientTemplates.RenderContext_Form) => string): CSR; /** Override Header rendering template. @param template New header template. */ - header(template: string): ICSR; - - /** Override Header rendering template. - @param template New header template. - */ - header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + header(template: string | RenderContext): CSR; /** Override Body rendering template. @param template New body template. */ - body(template: string): ICSR; - - /** Override Body rendering template. - @param template New body template. - */ - body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + body(template: string | RenderContext): CSR; /** Override Footer rendering template. @param template New footer template. */ - footer(template: string): ICSR; - - /** Override Footer rendering template. - @param template New footer template. - */ - footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + footer(template: string | RenderContext): CSR; /** Override View rendering template for specified field. @param fieldName Internal name of the field. @param template New View template. */ - fieldView(fieldName: string, template: string): ICSR; + fieldView(fieldName: string, template: string): CSR; /** Override View rendering template for specified field. @param fieldName Internal name of the field. @param template New View template. */ - fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; + // tslint:disable-next-line: unified-signatures + fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): CSR; /** Override DisplyForm rendering template for specified field. @param fieldName Internal name of the field. @param template New DisplyForm template. */ - fieldDisplay(fieldName: string, template: string): ICSR; + fieldDisplay(fieldName: string, template: string): CSR; /** Override DisplyForm rendering template. @param fieldName Internal name of the field. @param template New DisplyForm template. */ - fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + // tslint:disable-next-line: unified-signatures + fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): CSR; /** Override EditForm rendering template for specified field. @param fieldName Internal name of the field. @param template New EditForm template. */ - fieldEdit(fieldName: string, template: string): ICSR; + fieldEdit(fieldName: string, template: string): CSR; /** Override EditForm rendering template. @param fieldName Internal name of the field. @param template New EditForm template. */ - fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + // tslint:disable-next-line: unified-signatures + fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): CSR; /** Override NewForm rendering template for specified field. @param fieldName Internal name of the field. @param template New NewForm template. */ - fieldNew(fieldName: string, template: string): ICSR; + fieldNew(fieldName: string, template: string): CSR; /** Override NewForm rendering template. @param fieldName Internal name of the field. @param template New NewForm template. */ - fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + // tslint:disable-next-line: unified-signatures + fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): CSR; /** Set initial value for field. @param fieldName Internal name of the field. @param value Initial value for field. */ - setInitialValue(fieldName: string, value: any): ICSR; + setInitialValue(fieldName: string, value: any): CSR; /** Make field hidden in list view and standard forms. @param fieldName Internal name of the field. */ - makeHidden(fieldName: string): ICSR + makeHidden(fieldName: string): CSR; /** Replace New and Edit templates for field to Display template. @param fieldName Internal name of the field. */ - makeReadOnly(fieldName: string): ICSR + makeReadOnly(fieldName: string): CSR; /** Create cascaded Lookup Field. @param fieldName Internal name of the field. @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. */ - filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): CSR; /** Auto computes text-based field value based on another fields. @param targetField Internal name of the field. @param transform Function combines source field values. @param sourceField Internal names of source fields. */ - computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): CSR; /** Field text value with autocomplete based on autofill.js @param fieldName Internal name of the field. @param ctx AutoFill context. */ - autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR + autofill(fieldName: string, init: (ctx: AutoFillFieldContext) => () => void): CSR; /** Replace defult dropdown to search-based autocomplete for Lookup field. @param fieldName Internal name of the field. */ - seachLookup(fieldName: string): ICSR; + seachLookup(fieldName: string): CSR; /** Adds link to add new value to lookup list. @param fieldName Internal name of the field. @param prompt Text to display as a link to add new value. @param contentTypeID Default content type for new item. */ - lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): CSR; - koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; + koEditField(fieldName: string, template: string, vm: KoFieldInForm, dependencyFields?: string[]): CSR; } - export interface IAutoFillFieldContext { + export interface AutoFillFieldContext { renderContext: SPClientTemplates.RenderContext_FieldInForm; fieldContext: SPClientTemplates.ClientFormContext; autofill: SPClientAutoFill; control: HTMLInputElement; } - export interface IKoFieldInForm { - renderingContext?:SPClientTemplates.RenderContext_FieldInForm; - value?:KnockoutObservable; + export interface KoFieldInForm { + renderingContext?: SPClientTemplates.RenderContext_FieldInForm; + value?: KnockoutObservable; } - interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { - FormContextHook: IFormContextHook; + interface FormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { + FormContextHook: FormContextHook; } - interface IFormContextHook { - [fieldName: string]: IFormContextHookField; + interface FormContextHook { + [fieldName: string]: FormContextHookField; } - interface IFormContextHookField { + interface FormContextHookField { fieldSchema?: SPClientTemplates.FieldSchema_InForm; lastValue?: any; getValue?: () => any; @@ -1713,7 +1689,7 @@ namespace CSR { } - function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { + function ensureFormContextHookField(hook: FormContextHook, fieldName: string): FormContextHookField { return hook[fieldName] = hook[fieldName] || { updatedValueCallbacks: [] }; @@ -1730,7 +1706,7 @@ namespace CSR { } -if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { +if (typeof SP === 'object' && SP && typeof SP.SOD === 'object' && SP.SOD) { SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); } @@ -1741,15 +1717,15 @@ if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { namespace spdevlab { - export module mQuery { + export namespace mQuery { export class DynamicTable { // private fields - _domContainer:HTMLElement; - _tableContainer:MQueryResultSetElements; + _domContainer: HTMLElement; + _tableContainer: MQueryResultSetElements; - _rowTemplateId:string = null; - _rowTemplateContent:string = null; + _rowTemplateId: string = null; + _rowTemplateContent: string = null; _options = { tableCnt: '.spdev-rep-tb', @@ -1790,9 +1766,9 @@ namespace spdevlab { m$(this._tableContainer).append(this._rowTemplateContent); - m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { + m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click((e) => { - var targetElement = e.currentTarget; + var targetElement = e.currentTarget as HTMLElement; var parentRow = m$(targetElement).parents("tr").first(); m$(parentRow).remove(); @@ -1812,10 +1788,10 @@ namespace spdevlab { } } - static _templates:string[] = []; + static _templates: string[] = []; static initTables() { // init templates - m$('script').forEach((template:HTMLElement) => { + m$('script').forEach((template: HTMLElement) => { var id = m$(template).attr("dynamic-table-template-id"); @@ -1825,7 +1801,7 @@ namespace spdevlab { }); // init tables - m$(".spdev-rep-tb-cnt").forEach( divContainer => { + m$(".spdev-rep-tb-cnt").forEach(divContainer => { var dynamicTable = new DynamicTable(); @@ -1849,12 +1825,12 @@ m$.ready(() => { //whoisapppart.ts -module _ { +namespace _ { var queryString = parseQueryString(); - var isIframe = queryString['DisplayMode'] == 'iframe' + var isIframe = queryString['DisplayMode'] === 'iframe'; var spHostUrl = queryString['SPHostUrl']; var editmode = Number(queryString['editmode']); - var includeDetails = queryString['boolProp'] == 'true'; + var includeDetails = queryString['boolProp'] === 'true'; prepareVisual(); m$.ready(() => { @@ -1873,7 +1849,7 @@ module _ { AllowMultipleValues: false, Width: 300, OnUserResolvedClientScript: onUserResolvedClientScript - } + }; SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); } @@ -1905,6 +1881,8 @@ module _ { var properties = personProperties.get_userProfileProperties(); var messageText = ""; for (var key in properties) { + if(properties.hasOwnProperty(key)) + continue; messageText += "
[" + key + "]: \"" + properties[key] + "\""; } $get("detailInfo").innerHTML = messageText; @@ -1920,11 +1898,10 @@ module _ { function partProperties() { - if (editmode == 1) { + if (editmode === 1) { $get("editmodehdr").style.display = "inline"; $get("content").style.display = "none"; - } - else if (includeDetails) { + } else if (includeDetails) { $get('detailInfo').style.display = 'block'; $get("editmodehdr").style.display = "none"; @@ -1965,9 +1942,9 @@ module _ { var qs = document.location.search.split('?')[1]; if (qs) { var parts = qs.split('&'); - for (var i = 0; i < parts.length; i++) { - if (parts[i]) { - var pair = parts[i].split('='); + for (var part of parts) { + if (part) { + var pair = part.split('='); result[pair[0]] = decodeURIComponent(pair[1]); } } @@ -1984,12 +1961,12 @@ namespace MySP { /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ executeQueryPromise(): JQueryPromise { var deferred = jQuery.Deferred(); - this.executeQueryAsync(function (sender, args) { + this.executeQueryAsync(function done(sender, args) { deferred.resolve(sender, args); }, - function (sender, args) { - deferred.reject(sender, args); - }) + function fail(sender, args) { + deferred.reject(sender, args); + }); return deferred.promise(); } @@ -2007,7 +1984,7 @@ namespace MySP { SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); -module _ { +namespace _ { var context: MySP.ClientContextPromise; var web: SP.Web; var site: SP.Site; @@ -2018,12 +1995,12 @@ module _ { // This code runs when the DOM is ready and creates a context object // which is needed to use the SharePoint object model. // It also wires up the click handlers for the two HTML buttons in Default.aspx. - $(document).ready(function () { + $(document).ready(function onready() { context = MySP.ClientContextPromise.get_current(); site = context.get_site(); web = context.get_web(); - $('#listExisting').click(function () { listGroups(); }); - $('#createTerms').click(function () { createTerms(); }); + $('#listExisting').click(function listExistingClick() { listGroups(); }); + $('#createTerms').click(function createTermsClick() { createTerms(); }); }); // When the listExisting button is clicked, start by loading @@ -2097,44 +2074,44 @@ module _ { context.load(currentGroup); var termSets: SP.Taxonomy.TermSetCollection; context.executeQueryPromise() - .then( - () => { - // The group is now available becuase this is the - // success callback. So now we'll load and populate the - // term set collection. We have to do this before we can - // iterate through the collection, so we can do this - // with the following nested executeQueryAsync method call. - termSets = currentGroup.get_termSets(); - context.load(termSets); - return context.executeQueryPromise() - }) - .then(() => { - // The term sets are now available becuase this is the - // success callback. So now we'll iterate through the collection - // and create the clickable div. Also note how we create a - // click event handler for each div on-the-fly, and that we pass in the - // current group ID and term set ID to that function. So when the user - // clicks one of these divs, we will know which - // one was clicked by its term set ID, and to which group it belongs by its - // group ID. We also pass in the event object, so that we can cancel the bubble - // because this clickable div will be inside a parent clickable div and we - // don't want the parent's event to fire. - var termSetEnum = termSets.getEnumerator(); - while (termSetEnum.moveNext()) { - (() => { - var currentTermSet = termSetEnum.get_current(); - var termSetName = document.createElement("div"); - termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); - termSetName.setAttribute("style", "float:none;cursor:pointer;"); - var termSetID = currentTermSet.get_id(); - termSetName.setAttribute("id", termSetID.toString()); - $(termSetName).click(e => showTerms(e, groupID, termSetID)); - parentDiv.appendChild(termSetName); - })(); - } + .then( + () => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) + .then(() => { + // The term sets are now available becuase this is the + // success callback. So now we'll iterate through the collection + // and create the clickable div. Also note how we create a + // click event handler for each div on-the-fly, and that we pass in the + // current group ID and term set ID to that function. So when the user + // clicks one of these divs, we will know which + // one was clicked by its term set ID, and to which group it belongs by its + // group ID. We also pass in the event object, so that we can cancel the bubble + // because this clickable div will be inside a parent clickable div and we + // don't want the parent's event to fire. + var termSetEnum = termSets.getEnumerator(); + while (termSetEnum.moveNext()) { + (() => { + var currentTermSet = termSetEnum.get_current(); + var termSetName = document.createElement("div"); + termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); + termSetName.setAttribute("style", "float:none;cursor:pointer;"); + var termSetID = currentTermSet.get_id(); + termSetName.setAttribute("id", termSetID.toString()); + $(termSetName).click(e => showTerms(e, groupID, termSetID)); + parentDiv.appendChild(termSetName); + })(); + } - }) - .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); } @@ -2161,44 +2138,44 @@ module _ { // We need to load and populate the matching group first, or the // term sets that it contains will be inaccessible to our code. var currentGroup = groups.getById(groupID); - var termSets:SP.Taxonomy.TermSetCollection; - var currentTermSet:SP.Taxonomy.TermSet; - var terms:SP.Taxonomy.TermCollection; + var termSets: SP.Taxonomy.TermSetCollection; + var currentTermSet: SP.Taxonomy.TermSet; + var terms: SP.Taxonomy.TermCollection; context.load(currentGroup); context .executeQueryPromise() .then(() => { - // The group is now available becuase this is the - // success callback. So now we'll load and populate the - // term set collection. We have to do this before we can - // iterate through the collection, so we can do this - // with the following nested executeQueryAsync method call. - termSets = currentGroup.get_termSets(); - context.load(termSets); - return context.executeQueryPromise(); - }) + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) .then(() => { - currentTermSet = termSets.getById(termSetID); - context.load(currentTermSet); - return context.executeQueryPromise(); - }) + currentTermSet = termSets.getById(termSetID); + context.load(currentTermSet); + return context.executeQueryPromise(); + }) .then(() => { - terms = currentTermSet.get_terms(); - context.load(terms); - return context.executeQueryPromise(); - }) + terms = currentTermSet.get_terms(); + context.load(terms); + return context.executeQueryPromise(); + }) .then(() => { - var termsEnum = terms.getEnumerator(); - while (termsEnum.moveNext()) { - var currentTerm = termsEnum.get_current(); + var termsEnum = terms.getEnumerator(); + while (termsEnum.moveNext()) { + var currentTerm = termsEnum.get_current(); - var term = document.createElement("div"); - term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); - term.setAttribute("style", "float:none;margin-left:10px;"); - parentDiv.appendChild(term); - } - }) + var term = document.createElement("div"); + term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); + term.setAttribute("style", "float:none;margin-left:10px;"); + parentDiv.appendChild(term); + } + }) .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); } @@ -2297,61 +2274,61 @@ SP.SOD.execute('mquery.js', 'm$.ready', () => { function createPage(evt) { SP.SOD.execute('sp.js', 'SP.ClientConext', () => { SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { - var context = SP.ClientContext.get_current(); + var context = SP.ClientContext.get_current(); - var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); - var hostcontext = new SP.AppContextSite(context, hostUrl); - var web = hostcontext.get_web(); - var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); - context.load(web); - context.load(pubWeb); - context.executeQueryAsync( - // Success callback after getting the host Web as a PublishingWeb. - // We now want to add a new Publishing Page. - function () { - var pageInfo = new SP.Publishing.PublishingPageInformation(); - var newPage = pubWeb.addPublishingPage(pageInfo); - context.load(newPage); - context.executeQueryAsync( - function () { + var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); + var hostcontext = new SP.AppContextSite(context, hostUrl); + var web = hostcontext.get_web(); + var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); + context.load(web); + context.load(pubWeb); + context.executeQueryAsync( + // Success callback after getting the host Web as a PublishingWeb. + // We now want to add a new Publishing Page. + function done() { + var pageInfo = new SP.Publishing.PublishingPageInformation(); + var newPage = pubWeb.addPublishingPage(pageInfo); + context.load(newPage); + context.executeQueryAsync( + function done() { - // Success callback after adding a new Publishing Page. - // We want to get the actual list item that is represented by the Publishing Page. - var listItem = newPage.get_listItem(); - context.load(listItem); - context.executeQueryAsync( + // Success callback after adding a new Publishing Page. + // We want to get the actual list item that is represented by the Publishing Page. + var listItem = newPage.get_listItem(); + context.load(listItem); + context.executeQueryAsync( - // Success callback after getting the actual list item that is - // represented by the Publishing Page. - // We can now get its FieldValues, one of which is its FileLeafRef value. - // We can then use that value to build the Url to the new page - // and set the href or our link to that Url. - function () { - var link = document.getElementById("linkToPage"); - link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); - link.innerText = "Go to new page!"; - }, + // Success callback after getting the actual list item that is + // represented by the Publishing Page. + // We can now get its FieldValues, one of which is its FileLeafRef value. + // We can then use that value to build the Url to the new page + // and set the href or our link to that Url. + function done() { + var link = document.getElementById("linkToPage"); + link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); + link.innerText = "Go to new page!"; + }, - // Failure callback after getting the actual list item that is - // represented by the Publishing Page. - function (sender, args) { - alert('Failed to get new page: ' + args.get_message()); - } - ); - }, - // Failure callback after trying to add a new Publishing Page. - function (sender, args) { - alert('Failed to Add Page: ' + args.get_message()); - } + // Failure callback after getting the actual list item that is + // represented by the Publishing Page. + function fail(sender, args) { + alert('Failed to get new page: ' + args.get_message()); + } ); - }, - // Failure callback after trying to get the host Web as a PublishingWeb. - function (sender, args) { - alert('Failed to get the PublishingWeb: ' + args.get_message()); - } + }, + // Failure callback after trying to add a new Publishing Page. + function fail(sender, args) { + alert('Failed to Add Page: ' + args.get_message()); + } ); - }); + }, + // Failure callback after trying to get the host Web as a PublishingWeb. + function fail(sender, args) { + alert('Failed to get the PublishingWeb: ' + args.get_message()); + } + ); + }); }); } @@ -2370,16 +2347,16 @@ namespace SampleReputation { isLikedByCurrentUser: boolean; constructor(public row: SPClientTemplates.Item) { - this.id = parseInt(row['ID']); + this.id = parseInt(row['ID'], 10); this.title = row['Title']; - this.likesCount = parseInt(row['LikesCount']) || 0; + this.likesCount = parseInt(row['LikesCount'], 10) || 0; this.isLikedByCurrentUser = this.getLike(row['LikedBy']); } private getLike(likedBy): boolean { if (likedBy && likedBy.length > 0) { - for (var i = 0; i < likedBy.length; i++) { - if (likedBy[i].id == _spPageContextInfo.userId) { + for (var likedByItem of likedBy) { + if (likedByItem.id === _spPageContextInfo.userId) { return true; } } @@ -2413,10 +2390,10 @@ namespace SampleReputation { function renderTemplate(ctx: MyList) { var rows = ctx.ListData.Row; var result = ''; - for (var i = 0; i < rows.length; i++) { - var item = new MyItem(rows[i]); + for (var row of rows) { + var item = new MyItem(row); result += '\ -
  • ' + item.title +'\ +
  • ' + item.title + '\ \ ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ \ @@ -2431,13 +2408,13 @@ namespace SampleReputation { export function setLike(itemId: number, listId: string): void { var context = SP.ClientContext.get_current(); - var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; - SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { + var isLiked = m$('#likesCountText' + itemId)[0].textContent === '\u2661'; + SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function fail() { Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); context.executeQueryAsync( () => { m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); - var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); + var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent, 10); m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); }, (sender, args) => { @@ -2454,7 +2431,7 @@ namespace SampleReputation { //code from https://github.com/gandjustas/SharePointAngularTS namespace App { "use strict"; -var app = angular.module("app", []); + var app = angular.module("app", []); } // Install the angularjs.TypeScript.DefinitelyTyped NuGet package @@ -2472,17 +2449,17 @@ namespace App { static $inject: string[] = ["$SharePoint", "$spnotify"]; - constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { + constructor(private $SharePoint: App.SharePoint, private $n: App.SpNotify) { this.activate(); } activate() { - var loading = this.$n.showLoading(true) + var loading = this.$n.showLoading(true); this.$SharePoint .getLists() - .then(l => this.lists = l ) + .then(l => this.lists = l) .catch((e: string) => this.$n.show(e, true)) - .finally(() => this.$n.remove(loading) ); + .finally(() => this.$n.remove(loading)); ; } @@ -2496,11 +2473,11 @@ namespace App { namespace App { "use strict"; - export interface ISharePoint { + export interface SharePoint { getLists: () => ng.IPromise; } - class SharePointServcie implements ISharePoint { + class SharePointServcie implements SharePoint { static $inject: string[] = ["$q"]; constructor(public $q: ng.IQService) { @@ -2518,7 +2495,7 @@ namespace App { ctx.executeQueryAsync(() => { var result: SP.List[] = []; - for (var e = lists.getEnumerator(); e.moveNext();) { + for (var e = lists.getEnumerator(); e.moveNext(); /* nothing */) { result.push(e.get_current()); } promise.resolve(result); @@ -2537,13 +2514,13 @@ namespace App { namespace App { "use strict"; - export interface ISpNotify { - showLoading(sticky?: boolean) : string; + export interface SpNotify { + showLoading(sticky?: boolean): string; show(msg: string, sticky?: boolean): string; - remove(id: string):void; + remove(id: string): void; } - class SpNotify implements ISpNotify { + class NotifyImpl implements SpNotify { static $inject: string[] = []; @@ -2560,6 +2537,6 @@ namespace App { } } - angular.module("app").service("$spnotify", SpNotify); + angular.module("app").service("$spnotify", NotifyImpl); } diff --git a/sharepoint/tslint.json b/sharepoint/tslint.json new file mode 100644 index 0000000000..192203ab54 --- /dev/null +++ b/sharepoint/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file From e84fa2f77346d211d48c13db5489291b37d39bfa Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 17 Jan 2017 22:22:25 -0800 Subject: [PATCH 65/72] amqplib: Convert to external module style (#13974) --- amqplib/callback_api.d.ts | 59 +++++++++ amqplib/index.d.ts | 257 +++++++------------------------------- amqplib/properties.d.ts | 88 +++++++++++++ amqplib/tsconfig.json | 1 + amqplib/tslint.json | 6 + 5 files changed, 202 insertions(+), 209 deletions(-) create mode 100644 amqplib/callback_api.d.ts create mode 100644 amqplib/properties.d.ts create mode 100644 amqplib/tslint.json diff --git a/amqplib/callback_api.d.ts b/amqplib/callback_api.d.ts new file mode 100644 index 0000000000..5d025bf314 --- /dev/null +++ b/amqplib/callback_api.d.ts @@ -0,0 +1,59 @@ +import events = require('events'); +import { Replies, Options, Message } from './properties'; +export * from './properties'; + +export interface Connection extends events.EventEmitter { + close(callback?: (err: any) => void): void; + createChannel(callback: (err: any, channel: Channel) => void): void; + createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void; +} + +export interface Channel extends events.EventEmitter { + close(callback: (err: any) => void): void; + + assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err: any, ok: Replies.AssertQueue) => void): void; + checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void; + + deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err: any, ok: Replies.DeleteQueue) => void): void; + purgeQueue(queue: string, callback?: (err: any, ok: Replies.PurgeQueue) => void): void; + + bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void; + checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void; + + deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void; + + bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; + + cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void; + get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): void; + recover(callback?: (err: any, ok: Replies.Empty) => void): void; +} + +export interface ConfirmChannel extends Channel { + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + + waitForConfirms(callback?: (err: any) => void): void; +} + +export function connect(callback: (err: any, connection: Connection) => void): void; +export function connect(url: string, callback: (err: any, connection: Connection) => void): void; +export function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; diff --git a/amqplib/index.d.ts b/amqplib/index.d.ts index b406e00ac0..6cd326cd67 100644 --- a/amqplib/index.d.ts +++ b/amqplib/index.d.ts @@ -1,226 +1,65 @@ -// Type definitions for amqplib 0.5.x +// Type definitions for amqplib 0.5 // Project: https://github.com/squaremo/amqp.node // Definitions by: Michael Nahkies , Ab Reitsma , Nicolás Fantone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module 'amqplib' { - import * as Promise from 'bluebird'; - import * as events from 'events'; - import shared = require('amqplib/properties'); +import * as Promise from 'bluebird'; +import * as events from 'events'; +import { Replies, Options, Message } from './properties'; +export * from './properties'; - export import Replies = shared.Replies; - export import Options = shared.Options; - export import Message = shared.Message; - - export interface Connection extends events.EventEmitter { - close(): Promise; - createChannel(): Promise; - createConfirmChannel(): Promise; - } - - export interface Channel extends events.EventEmitter { - close(): Promise; - - assertQueue(queue: string, options?: Options.AssertQueue): Promise; - checkQueue(queue: string): Promise; - - deleteQueue(queue: string, options?: Options.DeleteQueue): Promise; - purgeQueue(queue: string): Promise; - - bindQueue(queue: string, source: string, pattern: string, args?: any): Promise; - unbindQueue(queue: string, source: string, pattern: string, args?: any): Promise; - - assertExchange(exchange: string, type: string, options?: Options.AssertExchange): Promise; - checkExchange(exchange: string): Promise; - - deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise; - - bindExchange(destination: string, source: string, pattern: string, args?: any): Promise; - unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise; - - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise; - - cancel(consumerTag: string): Promise; - get(queue: string, options?: Options.Get): Promise; - - ack(message: Message, allUpTo?: boolean): void; - ackAll(): void; - - nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; - nackAll(requeue?: boolean): void; - reject(message: Message, requeue?: boolean): void; - - prefetch(count: number, global?: boolean): Promise; - recover(): Promise; - } - - export interface ConfirmChannel extends Channel { - publish(exchange:string, routingKey:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean; - sendToQueue(queue:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean; - - waitForConfirms(): Promise; - } - - export function connect(url: string, socketOptions?: any): Promise; +export interface Connection extends events.EventEmitter { + close(): Promise; + createChannel(): Promise; + createConfirmChannel(): Promise; } -declare module 'amqplib/properties' { - export namespace Replies { - interface Empty { - } - interface AssertQueue { - queue: string; - messageCount: number; - consumerCount: number; - } - interface PurgeQueue { - messageCount: number; - } - interface DeleteQueue { - messageCount: number; - } - interface AssertExchange { - exchange: string; - } - interface Consume { - consumerTag: string; - } - } +export interface Channel extends events.EventEmitter { + close(): Promise; - export namespace Options { - interface AssertQueue { - exclusive?: boolean; - durable?: boolean; - autoDelete?: boolean; - arguments?: any; - messageTtl?: number; - expires?: number; - deadLetterExchange?: string; - deadLetterRoutingKey?: string; - maxLength?: number; - maxPriority?: number; - } - interface DeleteQueue { - ifUnused?: boolean; - ifEmpty?: boolean; - } - interface AssertExchange { - durable?: boolean; - internal?: boolean; - autoDelete?: boolean; - alternateExchange?: string; - arguments?: any; - } - interface DeleteExchange { - ifUnused?: boolean; - } - interface Publish { - expiration?: string | number; - userId?: string; - CC?: string | string[]; + assertQueue(queue: string, options?: Options.AssertQueue): Promise; + checkQueue(queue: string): Promise; - mandatory?: boolean; - persistent?: boolean; - deliveryMode?: boolean | number; - BCC?: string | string[]; + deleteQueue(queue: string, options?: Options.DeleteQueue): Promise; + purgeQueue(queue: string): Promise; - contentType?: string; - contentEncoding?: string; - headers?: any; - priority?: number; - correlationId?: string; - replyTo?: string; - messageId?: string; - timestamp?: number; - type?: string; - appId?: string; - } - interface Consume { - consumerTag?: string; - noLocal?: boolean; - noAck?: boolean; - exclusive?: boolean; - priority?: number; - arguments?: any; - } - interface Get { - noAck?: boolean; - } - } + bindQueue(queue: string, source: string, pattern: string, args?: any): Promise; + unbindQueue(queue: string, source: string, pattern: string, args?: any): Promise; - export interface Message { - content: Buffer; - fields: any; - properties: any; - } + assertExchange(exchange: string, type: string, options?: Options.AssertExchange): Promise; + checkExchange(exchange: string): Promise; + + deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise; + + bindExchange(destination: string, source: string, pattern: string, args?: any): Promise; + unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise; + + cancel(consumerTag: string): Promise; + get(queue: string, options?: Options.Get): Promise; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): Promise; + recover(): Promise; } -declare module 'amqplib/callback_api' { - import events = require('events'); - import shared = require('amqplib/properties') +export interface ConfirmChannel extends Channel { + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; - export import Replies = shared.Replies; - export import Options = shared.Options; - export import Message = shared.Message; - - export interface Connection extends events.EventEmitter { - close(callback?: (err: any) => void): void; - createChannel(callback: (err: any, channel: Channel) => void): void; - createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void; - } - - export interface Channel extends events.EventEmitter { - close(callback: (err: any) => void): void; - - assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err: any, ok: Replies.AssertQueue) => void): void; - checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void; - - deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err: any, ok: Replies.DeleteQueue) => void): void; - purgeQueue(queue: string, callback?: (err: any, ok: Replies.PurgeQueue) => void): void; - - bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - - assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void; - checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void; - - deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void; - - bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; - - cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void; - get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void; - - ack(message: Message, allUpTo?: boolean): void; - ackAll(): void; - - nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; - nackAll(requeue?: boolean): void; - reject(message: Message, requeue?: boolean): void; - - prefetch(count: number, global?: boolean): void; - recover(callback?: (err: any, ok: Replies.Empty) => void): void; - } - - export interface ConfirmChannel extends Channel { - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; - - waitForConfirms(callback?: (err: any) => void): void; - } - - export function connect(callback: (err: any, connection: Connection) => void): void; - export function connect(url: string, callback: (err: any, connection: Connection) => void): void; - export function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; + waitForConfirms(): Promise; } + +export function connect(url: string, socketOptions?: any): Promise; diff --git a/amqplib/properties.d.ts b/amqplib/properties.d.ts new file mode 100644 index 0000000000..12514d7810 --- /dev/null +++ b/amqplib/properties.d.ts @@ -0,0 +1,88 @@ +export namespace Replies { + interface Empty { + } + interface AssertQueue { + queue: string; + messageCount: number; + consumerCount: number; + } + interface PurgeQueue { + messageCount: number; + } + interface DeleteQueue { + messageCount: number; + } + interface AssertExchange { + exchange: string; + } + interface Consume { + consumerTag: string; + } +} + +export namespace Options { + interface AssertQueue { + exclusive?: boolean; + durable?: boolean; + autoDelete?: boolean; + arguments?: any; + messageTtl?: number; + expires?: number; + deadLetterExchange?: string; + deadLetterRoutingKey?: string; + maxLength?: number; + maxPriority?: number; + } + interface DeleteQueue { + ifUnused?: boolean; + ifEmpty?: boolean; + } + interface AssertExchange { + durable?: boolean; + internal?: boolean; + autoDelete?: boolean; + alternateExchange?: string; + arguments?: any; + } + interface DeleteExchange { + ifUnused?: boolean; + } + interface Publish { + expiration?: string | number; + userId?: string; + CC?: string | string[]; + + mandatory?: boolean; + persistent?: boolean; + deliveryMode?: boolean | number; + BCC?: string | string[]; + + contentType?: string; + contentEncoding?: string; + headers?: any; + priority?: number; + correlationId?: string; + replyTo?: string; + messageId?: string; + timestamp?: number; + type?: string; + appId?: string; + } + interface Consume { + consumerTag?: string; + noLocal?: boolean; + noAck?: boolean; + exclusive?: boolean; + priority?: number; + arguments?: any; + } + interface Get { + noAck?: boolean; + } +} + +export interface Message { + content: Buffer; + fields: any; + properties: any; +} \ No newline at end of file diff --git a/amqplib/tsconfig.json b/amqplib/tsconfig.json index e7bc5a878a..4c3f1a8477 100644 --- a/amqplib/tsconfig.json +++ b/amqplib/tsconfig.json @@ -15,6 +15,7 @@ }, "files": [ "index.d.ts", + "callback_api.d.ts", "amqplib-tests.ts" ] } \ No newline at end of file diff --git a/amqplib/tslint.json b/amqplib/tslint.json new file mode 100644 index 0000000000..9bc375c06b --- /dev/null +++ b/amqplib/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false + } +} \ No newline at end of file From 09ca98182812b9164c1d1efa51b928a21d071495 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 17 Jan 2017 22:23:01 -0800 Subject: [PATCH 66/72] bufferstream: Convert to external module style (#13975) --- bufferstream/index.d.ts | 162 ++++++++++++++--------------------- bufferstream/postbuffer.d.ts | 12 +++ bufferstream/tsconfig.json | 1 + bufferstream/tslint.json | 1 + 4 files changed, 80 insertions(+), 96 deletions(-) create mode 100644 bufferstream/postbuffer.d.ts create mode 100644 bufferstream/tslint.json diff --git a/bufferstream/index.d.ts b/bufferstream/index.d.ts index 69a16d98e0..ab048e437f 100644 --- a/bufferstream/index.d.ts +++ b/bufferstream/index.d.ts @@ -1,119 +1,89 @@ -// Type definitions for bufferstream v0.6.2 +// Type definitions for bufferstream 0.6 // Project: https://github.com/dodo/node-bufferstream // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module 'bufferstream' { - import stream = require('stream'); +import stream = require('stream'); - export = BufferStream; +export = BufferStream; - class BufferStream extends stream.Duplex { - constructor(options?: BufferStream.Opts); +declare class BufferStream extends stream.Duplex { + constructor(options?: BufferStream.Opts); - /* - different buffer behaviors can be triggered by size: + /* + different buffer behaviors can be triggered by size: - none when output drains, bufferstream drains too - flexible buffers everthing that it gets and not piping out - TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain - */ - setSize(size: string): void; // can be one of ['none', 'flexible', ] - setSize(size: number): void; // can be one of ['none', 'flexible', ] - /* - enables stream buffering default - */ - enable(): void; - /* - flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary. + none when output drains, bufferstream drains too + flexible buffers everthing that it gets and not piping out + TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain + */ + setSize(size: string | number): void; // can be one of ['none', 'flexible', ] + /* + enables stream buffering default + */ + enable(): void; + /* + flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary. - token[s] buffer splitters (should be String or Buffer) + token[s] buffer splitters (should be String or Buffer) - disables given tokens. wont flush until no splitter tokens are left. - */ - disable(): void; - disable(token: string, ...tokens: string[]): void; - disable(tokens: string[]): void; // Array - disable(token: Buffer, ...tokens: Buffer[]): void; - disable(tokens: Buffer[]): void; // Array - /* - each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data. + disables given tokens. wont flush until no splitter tokens are left. + */ + disable(tokens?: string[] | Buffer[]): void; + disable(token: string, ...tokens: string[]): void; + disable(token: Buffer, ...tokens: Buffer[]): void; + /* + each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data. - token[s] buffer splitters (should be String or Buffer) - */ - split(token: string, ...tokens: string[]): void; - split(tokens: string[]): void; // Array - split(token: Buffer, ...tokens: Buffer[]): void; - split(tokens: Buffer[]): void; // Array - /* - returns Buffer. - */ - getBuffer(): Buffer; - /* - returns Buffer. - */ - buffer: Buffer; - /* - shortcut for buffer.toString() - */ - toString(): string; - /* - shortcut for buffer.length - */ - length: number; - } - namespace BufferStream { - - export interface Opts { - /* - default encoding for writing strings - */ - encoding?: string; - /* - if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync) - */ - blocking?: boolean; - /* - defines buffer level or sets buffer to given size (see ↓setSize for more) - */ - size?: any; - /* - immediately call disable - */ - disabled?: boolean; - /* - short form for: - split(token, function (chunk) {emit('data', chunk)}) - */ - // String or Buffer - split?: any; - } - export var fn: {warn: boolean}; - } + token[s] buffer splitters (should be String or Buffer) + */ + split(tokens: string[] | Buffer[]): void; + split(token: string, ...tokens: string[]): void; + split(token: Buffer, ...tokens: Buffer[]): void; + /* + returns Buffer. + */ + getBuffer(): Buffer; + /* + returns Buffer. + */ + buffer: Buffer; + /* + shortcut for buffer.toString() + */ + toString(): string; + /* + shortcut for buffer.length + */ + length: number; } +declare namespace BufferStream { -declare module 'bufferstream/postbuffer' { - import http = require('http'); - import BufferStream = require('bufferstream'); - - class PostBuffer extends BufferStream { + export interface Opts { /* - for if you want to get all the post data from a http server request and do some db reqeust before. - - http client buffer + default encoding for writing strings */ - constructor(req: http.IncomingMessage); + encoding?: string; /* - set a callback to get all post data from a http server request + if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync) */ - onEnd(callback: (data: any) => void): void; + blocking?: boolean; /* - pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe + defines buffer level or sets buffer to given size (see ↓setSize for more) */ - pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; + size?: any; + /* + immediately call disable + */ + disabled?: boolean; + /* + short form for: + split(token, function (chunk) {emit('data', chunk)}) + */ + // String or Buffer + split?: any; } - - export = PostBuffer; + export var fn: {warn: boolean}; } diff --git a/bufferstream/postbuffer.d.ts b/bufferstream/postbuffer.d.ts new file mode 100644 index 0000000000..f8591771cc --- /dev/null +++ b/bufferstream/postbuffer.d.ts @@ -0,0 +1,12 @@ +import http = require('http'); +import BufferStream = require('./index'); + +export = PostBuffer; +declare class PostBuffer extends BufferStream { + /** for if you want to get all the post data from a http server request and do some db request before. */ + constructor(req: http.IncomingMessage); + /** set a callback to get all post data from a http server request */ + onEnd(callback: (data: any) => void): void; + /** pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe */ + pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; +} diff --git a/bufferstream/tsconfig.json b/bufferstream/tsconfig.json index 2d0055c5f2..4ae361153d 100644 --- a/bufferstream/tsconfig.json +++ b/bufferstream/tsconfig.json @@ -15,6 +15,7 @@ }, "files": [ "index.d.ts", + "postbuffer.d.ts", "bufferstream-tests.ts" ] } \ No newline at end of file diff --git a/bufferstream/tslint.json b/bufferstream/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/bufferstream/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file From 109fd152c01ee624f89da2f74c8669f18c460867 Mon Sep 17 00:00:00 2001 From: cbertiner Date: Wed, 18 Jan 2017 07:24:55 +0100 Subject: [PATCH 67/72] Add missing 'stops' property for AxisOptions (#13990) http://api.highcharts.com/highcharts/yAxis.stops --- highcharts/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index f0131bebe2..60a9fa15cb 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -805,6 +805,12 @@ declare namespace Highcharts { * @since 1.2.0 */ startOnTick?: boolean; + /** + * Solid gauge series only. Color stops for the solid gauge. + * Use this in cases where a linear gradient between a minColor and maxColor is not sufficient. + * The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color. + */ + stops?: [number, string][]; /** * The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within * a chart. This option overrides the tickPixelInterval option. From 8cc15342abddc60aaa74f55323b402f79c1e51b2 Mon Sep 17 00:00:00 2001 From: Andrey Kurdyumov Date: Wed, 18 Jan 2017 12:29:37 +0600 Subject: [PATCH 68/72] Support case when React Bootstrap used globally (#13983) --- react-bootstrap/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index 665c0cd1aa..7f89109ab1 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -5,6 +5,7 @@ import * as React from 'react'; export = ReactBootstrap; +export as namespace ReactBootstrap; declare namespace ReactBootstrap { From 1621a99587695d02b3371b07d456785472b2fc63 Mon Sep 17 00:00:00 2001 From: Toby Hede Date: Wed, 18 Jan 2017 17:31:00 +1100 Subject: [PATCH 69/72] Add AWS Lambda Handler function type definition (#13980) --- aws-lambda/aws-lambda-tests.ts | 5 ++++- aws-lambda/index.d.ts | 18 ++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index f54c3cc2d4..0d8d9bd47f 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -62,4 +62,7 @@ context.succeed(str); context.succeed(anyObj); context.succeed(str, anyObj); context.fail(error); -context.fail(str); \ No newline at end of file +context.fail(str); + +/* Handler */ +let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; diff --git a/aws-lambda/index.d.ts b/aws-lambda/index.d.ts index a5086eaadf..1aa41b9e62 100644 --- a/aws-lambda/index.d.ts +++ b/aws-lambda/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AWS Lambda // Project: http://docs.aws.amazon.com/lambda -// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Context @@ -17,7 +17,7 @@ interface Context { logStreamName: string; identity?: CognitoIdentity; clientContext?: ClientContext; - + // Functions getRemainingTimeInMillis(): number; @@ -28,7 +28,7 @@ interface Context { fail(message: string): void; succeed(message: string): void; succeed(object: any): void; - succeed(message: string, object: any): void; + succeed(message: string, object: any): void; } interface CognitoIdentity { @@ -58,6 +58,16 @@ interface ClientContextEnv { locale: string; } +/** + * AWS Lambda handler function. + * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html + * + * @param event – event data. + * @param context – runtime information of the Lambda function that is executing. + * @param callback – optional callback to return information to the caller, otherwise return value is null. + */ +export type Handler = (event: any, context: Context, callback?: Callback) => void; + /** * Optional callback parameter. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html @@ -67,4 +77,4 @@ interface ClientContextEnv { */ export type Callback = (error?: Error, result?: any) => void; -export as namespace AWSLambda; \ No newline at end of file +export as namespace AWSLambda; From 25a0880570c1555eba0a6b664d0d687cf131b11b Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 18 Jan 2017 06:37:55 +0000 Subject: [PATCH 70/72] Material UI - OnChange text field (#13970) Modified the signature of OnChange for the Text Field. --- material-ui/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 08e926d043..716505987d 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -1765,7 +1765,7 @@ declare namespace __MaterialUI { multiLine?: boolean; name?: string; onBlur?: React.FocusEventHandler<{}>; - onChange?: React.FormEventHandler<{}>; + onChange?: (e: React.FormEvent<{}>, newValue: string) => void; onEnterKeyDown?: React.KeyboardEventHandler<{}>; onFocus?: React.FocusEventHandler<{}>; onKeyDown?: React.KeyboardEventHandler<{}>; From b422c432ddca8ca734ba05bb2f7f25b815a8dd43 Mon Sep 17 00:00:00 2001 From: Pavel Puchkov <0x6368656174@gmail.com> Date: Wed, 18 Jan 2017 16:40:41 +1000 Subject: [PATCH 71/72] Add types for https://github.com/jaredhanson/passport-anonymous (#14016) * Add "movieImages()" method, add "language" opional parametr * Change Definitions by * Add types for https://github.com/jaredhanson/connect-ensure-login * Add tslint.json for connect-ensure-login * Remove module from connect-ensure-login * Set strictNullChecks to true in connect-ensure-login * Add definitions for https://github.com/jaredhanson/passport-anonymous * Fix tests * fix import * fix import --- passport-anonymous/index.d.ts | 10 ++++++++++ .../passport-anonymous-tests.ts | 4 ++++ passport-anonymous/tsconfig.json | 20 +++++++++++++++++++ passport-anonymous/tslint.json | 3 +++ 4 files changed, 37 insertions(+) create mode 100644 passport-anonymous/index.d.ts create mode 100644 passport-anonymous/passport-anonymous-tests.ts create mode 100644 passport-anonymous/tsconfig.json create mode 100644 passport-anonymous/tslint.json diff --git a/passport-anonymous/index.d.ts b/passport-anonymous/index.d.ts new file mode 100644 index 0000000000..a7c9e5b332 --- /dev/null +++ b/passport-anonymous/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for passport-anonymous 1.0 +// Project: https://github.com/jaredhanson/passport-anonymous +// Definitions by: Pavel Puchkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as passport from "passport"; + +export class Strategy implements passport.Strategy { + authenticate: () => void; +} \ No newline at end of file diff --git a/passport-anonymous/passport-anonymous-tests.ts b/passport-anonymous/passport-anonymous-tests.ts new file mode 100644 index 0000000000..3daa2474cf --- /dev/null +++ b/passport-anonymous/passport-anonymous-tests.ts @@ -0,0 +1,4 @@ +import * as passport from "passport"; +import { Strategy } from "passport-anonymous"; + +passport.use(new Strategy()); diff --git a/passport-anonymous/tsconfig.json b/passport-anonymous/tsconfig.json new file mode 100644 index 0000000000..8414fad459 --- /dev/null +++ b/passport-anonymous/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "passport-anonymous-tests.ts" + ] +} \ No newline at end of file diff --git a/passport-anonymous/tslint.json b/passport-anonymous/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/passport-anonymous/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} From c5506327ca9c78a389abc6693e25185456b04187 Mon Sep 17 00:00:00 2001 From: Linda_pp Date: Wed, 18 Jan 2017 17:44:10 +0900 Subject: [PATCH 72/72] Add 'jenkins' module (#14047) * Add 'jenkins' module * jenkins: Prefer any to Object * jenkins: Remove duplicates * jenkins: Forgot adding tslint.json * jenkins: improve Function types and underlying value type of promises * jenkins: fix header and extra overloads * jenkins: Add test for promisified APIs * jenkins: Enable strict null checks --- jenkins/index.d.ts | 143 +++++++++++++++++++++++++++ jenkins/jenkins-tests.ts | 205 +++++++++++++++++++++++++++++++++++++++ jenkins/tsconfig.json | 20 ++++ jenkins/tslint.json | 1 + 4 files changed, 369 insertions(+) create mode 100644 jenkins/index.d.ts create mode 100644 jenkins/jenkins-tests.ts create mode 100644 jenkins/tsconfig.json create mode 100644 jenkins/tslint.json diff --git a/jenkins/index.d.ts b/jenkins/index.d.ts new file mode 100644 index 0000000000..5db91893a6 --- /dev/null +++ b/jenkins/index.d.ts @@ -0,0 +1,143 @@ +// Type definitions for jenkins 0.20 +// Project: https://github.com/silas/node-jenkins +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace create { + interface JenkinsAPI { + info(callback: (err: Error, data: any) => void): void; + build: { + get(name: string, n: number, callback: (err: Error, data: any) => void): void; + log(name: string, callback: (err: Error, data: any) => void): void; + log(name: string, n: number, callback: (err: Error, data: any) => void): void; + log(name: string, n: number, start: number, callback: (err: Error, data: any) => void): void; + log(name: string, n: number, start: number, type: 'text' | 'html', callback: (err: Error, data: any) => void): void; + log(name: string, n: number, start: number, type: 'text' | 'html', meta: boolean, callback: (err: Error, data: any) => void): void; + logStream(name: string, n: number, type?: 'text' | 'html', delay?: number): NodeJS.ReadableStream; + stop(name: string, n: number, callback: (err: Error) => void): void; + }; + job: { + build(name: string | JobBuildOptions, callback: (err: Error, data: any) => void): void; + build(name: string, parameters: any, callback: (err: Error, data: any) => void): void; + build(name: string, parameters: any, token: string, callback: (err: Error, data: any) => void): void; + config(name: string, callback: (err: Error, data: any) => void): void; + config(name: string, xml: string, callback: (err: Error, data: any) => void): void; + copy(name: string, from: string, callback: (err: Error) => void): void; + create(name: string, xml: string, callback: (err: Error) => void): void; + destroy(name: string, callback: (err: Error) => void): void; + disable(name: string, callback: (err: Error) => void): void; + enable(name: string, callback: (err: Error) => void): void; + exists(name: string, callback: (err: Error, exists: boolean) => void): void; + get(name: string, callback: (err: Error, data: any) => void): void; + list(callback: (err: Error, data: any) => void): void; + }; + node: { + config(name: string, callback: (err: Error, data: any) => void): void; + create(name: string, callback: (err: Error) => void): void; + destroy(name: string, callback: (err: Error) => void): void; + disconnect(name: string, callback: (err: Error) => void): void; + disconnect(name: string, message: string, callback: (err: Error) => void): void; + disable(name: string, callback: (err: Error) => void): void; + disable(name: string, message: string, callback: (err: Error) => void): void; + enable(name: string, callback: (err: Error) => void): void; + exists(name: string, callback: (err: Error, data: boolean) => void): void; + get(name: string, callback: (err: Error, data: any) => void): void; + list(callback: (err: Error, data: any) => void): void; + list(full: boolean, callback: (err: Error, data: any) => void): void; + }; + queue: { + list(callback: (err: Error, data: any) => void): void; + item(n: number, callback: (err: Error, data: any) => void): void; + cancel(n: number, callback: (err: Error) => void): void; + }; + view: { + config(name: string, callback: (err: Error, data: any) => void): void; + config(name: string, xml: string, callback: (err: Error, data: any) => void): void; + create(name: string, type: 'list' | 'my', callback: (err: Error) => void): void; + destroy(name: string, callback: (err: Error) => void): void; + exists(name: string, callback: (err: Error, exists: boolean) => void): void; + get(name: string, callback: (err: Error, data: any) => void): void; + list(callback: (err: Error, data: any) => void): void; + add(name: string, job: string, callback: (err: Error) => void): void; + remove(name: string, job: string, callback: (err: Error) => void): void; + }; + } + + export interface JenkinsPromisifiedAPI { + info(): Promise; + build: { + get(name: string, n: number): Promise; + log(name: string, n: number, start?: number, type?: 'text' | 'html', meta?: boolean): Promise; + logStream(name: string, n: number, type?: 'text' | 'html', delay?: number): Promise; + stop(name: string, n: number): Promise; + }; + job: { + build(name: string, parameters?: any, token?: string): Promise; + build(opts: JobBuildOptions): Promise; + config(name: string, xml?: string): Promise; + copy(name: string, from: string): Promise; + create(name: string, xml: string): Promise; + destroy(name: string): Promise; + disable(name: string): Promise; + enable(name: string): Promise; + exists(name: string): Promise; + get(name: string): Promise; + list(): Promise; + }; + node: { + config(name: string): Promise; + create(name: string): Promise; + destroy(name: string): Promise; + disconnect(name: string, message?: string): Promise; + disable(name: string, message?: string): Promise; + enable(name: string): Promise; + exists(name: string): Promise; + get(name: string): Promise; + list(full?: boolean): Promise; + }; + queue: { + list(): Promise; + item(n: number): Promise; + cancel(n: number): Promise; + }; + view: { + config(name: string, xml?: string): Promise; + create(name: string, type: 'list' | 'my'): Promise; + destroy(name: string): Promise; + exists(name: string): Promise; + get(name: string): Promise; + list(): Promise; + add(name: string, job: string): Promise; + remove(name: string, job: string): Promise; + }; + } + + interface JobBuildOptions { + name: string; + parameters?: any; + token?: string; + } + + interface JenkinsClientOptions { + baseUrl?: string; + crumbIssuer?: boolean; + headers?: any; + promisify?: boolean | ((...args: any[]) => any); + } +} + +declare function create(opts?: { + baseUrl?: string; + crumbIssuer?: boolean; + headers?: any; + promisify?: false; + }): create.JenkinsAPI; +declare function create(opts: { + baseUrl?: string; + crumbIssuer?: boolean; + headers?: any; + promisify: true; + }): create.JenkinsPromisifiedAPI; +export = create; diff --git a/jenkins/jenkins-tests.ts b/jenkins/jenkins-tests.ts new file mode 100644 index 0000000000..c3def89156 --- /dev/null +++ b/jenkins/jenkins-tests.ts @@ -0,0 +1,205 @@ +import * as J from 'jenkins'; + +const jenkins = J({ baseUrl: 'http://user:pass@localhost:8080', crumbIssuer: true }); + +jenkins.info(function(err, data) { + if (err) throw err; + + console.log('info', data); +}); + +jenkins.build.get('example', 1, function(err, data) { + if (err) throw err; + + console.log('build', data); +}); + +jenkins.build.log('example', 1, function(err, data) { + if (err) throw err; + + console.log('log', data); +}); + +var log = jenkins.build.logStream('example', 1); + +log.on('data', function(text: string) { + process.stdout.write(text); +}); + +log.on('error', function(err: Error) { + console.log('error', err); +}); + +log.on('end', function() { + console.log('end'); +}); + +jenkins.build.stop('example', 1, function(err) { + if (err) throw err; +}); + +jenkins.job.build('example', function(err, data) { + if (err) throw err; + + console.log('queue item number', data); +}); + +jenkins.job.build({ name: 'example', parameters: { name: 'value' } }, function(err) { + if (err) throw err; +}); + +jenkins.job.config('example', function(err, data) { + if (err) throw err; + + console.log('xml', data); +}); + +jenkins.job.config('example', '', function(err) { + if (err) throw err; +}); + +jenkins.job.copy('fromJob', 'example', function(err) { + if (err) throw err; +}); + +jenkins.job.create('example', '', function(err) { + if (err) throw err; +}); + +jenkins.job.destroy('example', function(err) { + if (err) throw err; +}); + +jenkins.job.disable('example', function(err) { + if (err) throw err; +}); + +jenkins.job.enable('example', function(err) { + if (err) throw err; +}); + +jenkins.job.exists('example', function(err, exists) { + if (err) throw err; + + console.log('exists', exists); +}); + +jenkins.job.get('example', function(err, data) { + if (err) throw err; + + console.log('job', data); +}); + +jenkins.job.list(function(err, data) { + if (err) throw err; + + console.log('jobs', data); +}); + +jenkins.node.config('example', function(err, data) { + if (err) throw err; + + console.log('xml', data); +}); + +jenkins.node.create('slave', function(err) { + if (err) throw err; +}); + +jenkins.node.destroy('slave', function(err) { + if (err) throw err; +}); + +jenkins.node.disconnect('slave', 'no longer used', function(err) { + if (err) throw err; +}); + +jenkins.node.disable('slave', 'network failure', function(err) { + if (err) throw err; +}); + +jenkins.node.enable('slave', function(err) { + if (err) throw err; +}); + +jenkins.node.exists('slave', function(err, exists) { + if (err) throw err; + + console.log('exists', exists); +}); + +jenkins.node.get('slave', function(err, data) { + if (err) throw err; + + console.log('node', data); +}); + +jenkins.node.list(function(err, data) { + if (err) throw err; + + console.log('nodes', data); +}); + +jenkins.queue.list(function(err, data) { + if (err) throw err; + + console.log('queues', data); +}); + +jenkins.queue.item(130, function(err, data) { + if (err) throw err; + + console.log('item', data); +}); + +jenkins.queue.cancel(23, function(err) { + if (err) throw err; +}); + +jenkins.view.config('example', function(err, data) { + if (err) throw err; + + console.log('xml', data); +}); + +jenkins.view.config('example', '', function(err) { + if (err) throw err; +}); + +jenkins.view.create('example', 'list', function(err) { + if (err) throw err; +}); + +jenkins.view.destroy('example', function(err) { + if (err) throw err; +}); + +jenkins.view.exists('example', function(err, exists) { + if (err) throw err; + + console.log('exists', exists); +}); + +jenkins.view.get('example', function(err, data) { + if (err) throw err; + + console.log('view', data); +}); + +jenkins.view.list(function(err, data) { + if (err) throw err; + + console.log('views', data); +}); + +jenkins.view.add('example', 'jobExample', function(err) { + if (err) throw err; +}); + +jenkins.view.remove('example', 'jobExample', function(err) { + if (err) throw err; +}); + +const jenkins2 = J({ baseUrl: 'http://user:pass@localhost:8080', crumbIssuer: true, promisify: true }); +jenkins2.info().then(info => console.log(info)); +jenkins2.job.exists('example').then(exists => { var b: boolean = exists; }); diff --git a/jenkins/tsconfig.json b/jenkins/tsconfig.json new file mode 100644 index 0000000000..281f16ab67 --- /dev/null +++ b/jenkins/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jenkins-tests.ts" + ] +} diff --git a/jenkins/tslint.json b/jenkins/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/jenkins/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" }