From 8b7eef80b33e68fccd01f30106f00a63050dcece Mon Sep 17 00:00:00 2001 From: Joseph Vaughan Date: Mon, 14 Dec 2015 13:54:03 +0000 Subject: [PATCH 01/72] Add definitions for CodeMirror's runmode addon --- codemirror/codemirror-runmode-tests.ts | 6 ++++++ codemirror/codemirror-runmode.d.ts | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 codemirror/codemirror-runmode-tests.ts create mode 100644 codemirror/codemirror-runmode.d.ts diff --git a/codemirror/codemirror-runmode-tests.ts b/codemirror/codemirror-runmode-tests.ts new file mode 100644 index 000000000..e139e7177 --- /dev/null +++ b/codemirror/codemirror-runmode-tests.ts @@ -0,0 +1,6 @@ +/// +/// + +var query = "SELECT * FROM Table"; + +CodeMirror.runMode(query, "text/x-sql", document.body); diff --git a/codemirror/codemirror-runmode.d.ts b/codemirror/codemirror-runmode.d.ts new file mode 100644 index 000000000..89f35602f --- /dev/null +++ b/codemirror/codemirror-runmode.d.ts @@ -0,0 +1,22 @@ +// Type definitions for CodeMirror +// Project: https://github.com/marijnh/CodeMirror +// Definitions by: Joseph Vaughan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// See docs https://codemirror.net/doc/manual.html#addon_runmode + +declare module CodeMirror { + + /** + * Can be used to run a CodeMirror mode over text without actually opening an editor instance. + * + * @param text The document to run through the highlighter. + * @param mode The mode to use (must be loaded as normal). + * @param output If this is a function, it will be called for each token with + * two arguments, the token's text and the token's style class + * (may be null for unstyled tokens). If it is a DOM node, the + * tokens will be converted to span elements as in an editor, + * and inserted into the node (through innerHTML). + */ + function runMode(text : string, mode : any, output : any): void; +} From 38223f88dbb127d341aca6205c84dd51fc295657 Mon Sep 17 00:00:00 2001 From: Joseph Vaughan Date: Mon, 21 Dec 2015 13:59:31 +0000 Subject: [PATCH 02/72] Improve types for CodeMirror's runmode addon --- codemirror/codemirror-runmode.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codemirror/codemirror-runmode.d.ts b/codemirror/codemirror-runmode.d.ts index 89f35602f..58a8330a8 100644 --- a/codemirror/codemirror-runmode.d.ts +++ b/codemirror/codemirror-runmode.d.ts @@ -8,7 +8,7 @@ declare module CodeMirror { /** - * Can be used to run a CodeMirror mode over text without actually opening an editor instance. + * Runs a CodeMirror mode over text without opening an editor instance. * * @param text The document to run through the highlighter. * @param mode The mode to use (must be loaded as normal). @@ -18,5 +18,5 @@ declare module CodeMirror { * tokens will be converted to span elements as in an editor, * and inserted into the node (through innerHTML). */ - function runMode(text : string, mode : any, output : any): void; + function runMode(text: string, modespec: any, callback: (HTMLElement | ((text: string, style: string) => void)), options? : { tabSize?: number; state?: any; }): void; } From 40191cf78c581ec6b356ffe138a333a0996672f4 Mon Sep 17 00:00:00 2001 From: David Gardiner Date: Thu, 18 Feb 2016 16:12:44 +1030 Subject: [PATCH 03/72] Remove circular dependency express.d.ts and serve-static.d.ts had a circular dependency, which causes NuGet pain. Extract core definitions from express.d.ts and move them to express-serve-static-core.d.ts Update serve-static.d.ts to depend on express-serve-static-core.d.ts --- .../express-serve-static-core-tests.ts | 5 + .../express-serve-static-core.d.ts | 1063 ++++++++++++++++ express/express.d.ts | 1085 +---------------- serve-static/serve-static-tests.ts | 1 + serve-static/serve-static.d.ts | 4 +- 5 files changed, 1100 insertions(+), 1058 deletions(-) create mode 100644 express-serve-static-core/express-serve-static-core-tests.ts create mode 100644 express-serve-static-core/express-serve-static-core.d.ts diff --git a/express-serve-static-core/express-serve-static-core-tests.ts b/express-serve-static-core/express-serve-static-core-tests.ts new file mode 100644 index 000000000..a89769c93 --- /dev/null +++ b/express-serve-static-core/express-serve-static-core-tests.ts @@ -0,0 +1,5 @@ +/// + +import * as express from 'express-serve-static-core'; + +// null test file - everything should be tested from express.d.ts and serve-static.d.ts \ No newline at end of file diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts new file mode 100644 index 000000000..b0fb1f36d --- /dev/null +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -0,0 +1,1063 @@ +// Type definitions for Express 4.x +// Project: http://expressjs.com +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// This extracts the core definitions from express to prevent a circular dependency between express and serve-static +/// + +declare module Express { + + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } +} + +declare module "express-serve-static-core" { + import * as http from "http"; + + interface IRoute { + path: string; + stack: any; + all(...handler: RequestHandler[]): IRoute; + get(...handler: RequestHandler[]): IRoute; + post(...handler: RequestHandler[]): IRoute; + put(...handler: RequestHandler[]): IRoute; + delete(...handler: RequestHandler[]): IRoute; + patch(...handler: RequestHandler[]): IRoute; + options(...handler: RequestHandler[]): IRoute; + head(...handler: RequestHandler[]): IRoute; + } + + interface IRouterMatcher { + (name: string | RegExp, ...handlers: RequestHandler[]): T; + } + + interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn + */ + param(name: string, handler: RequestParamHandler): T; + param(name: string, matcher: RegExp): T; + param(name: string, mapper: (param: any) => any): T; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; + + route(path: string): IRoute; + + use(...handler: RequestHandler[]): T; + use(handler: ErrorRequestHandler | RequestHandler): T; + use(path: string, ...handler: RequestHandler[]): T; + use(path: string, handler: ErrorRequestHandler | RequestHandler): T; + use(path: string[], ...handler: RequestHandler[]): T; + use(path: string[], handler: ErrorRequestHandler): T; + use(path: RegExp, ...handler: RequestHandler[]): T; + use(path: RegExp, handler: ErrorRequestHandler): T; + use(path: string, router: Router): T; + } + + + export interface Router extends IRouter { } + + interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean; + } + + interface Errback { (err: Error): void; } + + interface Request extends http.ServerRequest, Express.Request { + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get(name: string): string; + + header(name: string): string; + + headers: { [key: string]: string; }; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(type: string): string; + + accepts(type: string[]): string; + + /** + * Returns the first accepted charset of the specified character sets, + * based on the request’s Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param charset + */ + acceptsCharsets(charset?: string | string[]): string[]; + + /** + * Returns the first accepted encoding of the specified encodings, + * based on the request’s Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param encoding + */ + acceptsEncodings(encoding?: string | string[]): string[]; + + /** + * Returns the first accepted language of the specified languages, + * based on the request’s Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * + * @param lang + */ + acceptsLanguages(lang?: string | string[]): string[]; + + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): any[]; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): boolean; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + hostname: string; + + /** + * @deprecated Use hostname instead. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + //body: { username: string; password: string; remember: boolean; title: string; }; + body: any; + + //cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: any; + + user: any; + + authenticatedUser: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + + baseUrl: string; + + app: Application; + } + + interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; + } + + interface Send { + (status: number, body?: any): Response; + (body: any): Response; + } + + interface Response extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): Response; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Response; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): Response; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ + sendFile(path: string): void; + sendFile(path: string, options: any): void; + sendFile(path: string, fn: Errback): void; + sendFile(path: string, options: any, fn: Errback): void; + + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, fn: Errback): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ + download(path: string): void; + download(path: string, filename: string): void; + download(path: string, fn: Errback): void; + download(path: string, filename: string, fn: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + contentType(type: string): Response; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + type(type: string): Response; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): Response; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): Response; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): Response; + set(field: string, value?: string): Response; + + header(field: any): Response; + header(field: string, value?: string): Response; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** + * Get value for header `field`. + * + * @param field + */ + get(field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): Response; + cookie(name: string, val: any, options: CookieOptions): Response; + cookie(name: string, val: any): Response; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string): Response; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(view: string, callback?: (err: Error, html: string) => void): void; + + locals: any; + + charset: string; + } + + interface NextFunction { + (): void; + (err: any): void; + } + + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; + } + + + interface Handler extends RequestHandler { } + + interface RequestParamHandler { + (req: Request, res: Response, next: NextFunction, param: any): any; + } + + interface Application extends IRouter, Express.Application { + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set(setting: string, val: any): Application; + get: { + (name: string): any; // Getter + (name: string | RegExp, ...handlers: RequestHandler[]): Application; + }; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): boolean; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): Application; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): Application; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(fn: Function): Application; + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; + listen(port: number, hostname: string, callback?: Function): http.Server; + listen(port: number, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + + route(path: string): IRoute; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + } + + interface Express extends Application { + /** + * Framework version. + */ + version: string; + + /** + * Expose mime. + */ + mime: string; + + (): Application; + + /** + * Create an express application. + */ + createApplication(): Application; + + createServer(): Application; + + application: any; + + request: Request; + + response: Response; + } + + interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; + } +} \ No newline at end of file diff --git a/express/express.d.ts b/express/express.d.ts index 3404ce903..aedbc3851 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -10,1071 +10,44 @@ =============================================== */ -/// /// - -declare module Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - +/// declare module "express" { - import * as http from "http"; import * as serveStatic from "serve-static"; + import * as core from "express-serve-static-core"; - function e(): e.Express; + /** + * Creates an Express application. The express() function is a top-level function exported by the express module. + */ + function e(): core.Express; module e { - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - head(...handler: RequestHandler[]): IRoute; - } - - interface IRouterMatcher { - (name: string|RegExp, ...handlers: RequestHandler[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; - - route(path: string): IRoute; - - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler|RequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler|RequestHandler): T; - use(path: string[], ...handler: RequestHandler[]): T; - use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandler[]): T; - use(path: RegExp, handler: ErrorRequestHandler): T; - use(path:string, router:Router): T; - } - - export function Router(options?: any): Router; - - export interface Router extends IRouter {} - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.ServerRequest, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get (name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(type: string): string; - - accepts(type: string[]): string; - - /** - * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. - * If none of the specified charsets is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param charset - */ - acceptsCharsets(charset?: string|string[]): string[]; - - /** - * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. - * If none of the specified encodings is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param encoding - */ - acceptsEncodings(encoding?: string|string[]): string[]; - - /** - * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. - * If none of the specified languages is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * - * @param lang - */ - acceptsLanguages(lang?: string|string[]): string[]; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - hostname: string; - - /** - * @deprecated Use hostname instead. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - user: any; - - authenticatedUser: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - - baseUrl: string; - - app: Application; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, fn: Errback): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get (field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - render(view: string, callback?: (err: Error, html: string) => void ): void; - - locals: any; - - charset: string; - } - - interface NextFunction { - (): void; - (err: any): void; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } - - interface Handler extends RequestHandler {} - - interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, param: any): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string|RegExp, ...handlers: RequestHandler[]): Application; - }; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - route(path: string): IRoute; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. - */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } + /** + * This is the only built-in middleware function in Express. It serves static files and is based on serve-static. + */ var static: typeof serveStatic; + + export function Router(options?: any): core.Router; + + interface Application extends core.Application { } + interface CookieOptions extends core.CookieOptions { } + interface Errback extends core.Errback { } + interface ErrorRequestHandler extends core.ErrorRequestHandler { } + interface Express extends core.Express { } + interface Handler extends core.Handler { } + interface IRoute extends core.IRoute { } + interface IRouter extends core.IRouter { } + interface IRouterMatcher extends core.IRouterMatcher { } + interface MediaType extends core.MediaType { } + interface NextFunction extends core.NextFunction { } + interface Request extends core.Request { } + interface RequestHandler extends core.RequestHandler { } + interface RequestParamHandler extends core.RequestParamHandler { } + export interface Response extends core.Response { } + interface Router extends core.Router { } + interface Send extends core.Send { } } export = e; diff --git a/serve-static/serve-static-tests.ts b/serve-static/serve-static-tests.ts index 9813794a6..7435ed3ab 100644 --- a/serve-static/serve-static-tests.ts +++ b/serve-static/serve-static-tests.ts @@ -1,4 +1,5 @@ /// +/// import * as express from 'express'; import * as serveStatic from 'serve-static'; diff --git a/serve-static/serve-static.d.ts b/serve-static/serve-static.d.ts index 29e5276cf..21c18ea14 100644 --- a/serve-static/serve-static.d.ts +++ b/serve-static/serve-static.d.ts @@ -10,11 +10,11 @@ =============================================== */ -/// +/// /// declare module "serve-static" { - import * as express from "express"; + import * as express from "express-serve-static-core"; /** * Create a new middleware function to serve files from within a given root directory. From e2158078bab5ac5446698d5b2f1873296e2383cc Mon Sep 17 00:00:00 2001 From: Michael DESIGAUD Date: Wed, 24 Feb 2016 18:50:47 +0100 Subject: [PATCH 04/72] Add phonegap nfc plugin typing --- phonegap-nfc/PhoneGapNfc-ndef-tests.ts | 27 ++ phonegap-nfc/PhoneGapNfc-nfc-tests.ts | 50 +++ phonegap-nfc/PhoneGapNfc.d.ts | 456 +++++++++++++++++++++++++ 3 files changed, 533 insertions(+) create mode 100644 phonegap-nfc/PhoneGapNfc-ndef-tests.ts create mode 100644 phonegap-nfc/PhoneGapNfc-nfc-tests.ts create mode 100644 phonegap-nfc/PhoneGapNfc.d.ts diff --git a/phonegap-nfc/PhoneGapNfc-ndef-tests.ts b/phonegap-nfc/PhoneGapNfc-ndef-tests.ts new file mode 100644 index 000000000..29b8c1326 --- /dev/null +++ b/phonegap-nfc/PhoneGapNfc-ndef-tests.ts @@ -0,0 +1,27 @@ +/// + +let record:NdefRecord = ndef.record(0x01,[0x0F],[0x0C],[0xFF]); + +record = ndef.textRecord('textRecord','fr',[24,78]); + +record = ndef.uriRecord('uriRecord',[24,78]); + +record = ndef.absoluteUriRecord('uriRecord',[88,142],[24,78]); + +record = ndef.mimeMediaRecord('text/json',[88,142],[24,78]); + +record = ndef.smartPoster([],[88,142]); + +record = ndef.emptyRecord(); + +record = ndef.androidApplicationRecord('fr.redfroggy.phonegap'); + +let bytes:Array = ndef.encodeMessage([]); + +let records:Array = ndef.decodeMessage(bytes); + +let obj:any = ndef.decodeTnf(bytes[0]); + +let tnfByte:number = ndef.encodeTnf(bytes[0],bytes[1],bytes[2],bytes[3],bytes[4],bytes[5]); + +let tnfString:string = ndef.tnfToString(tnfByte); diff --git a/phonegap-nfc/PhoneGapNfc-nfc-tests.ts b/phonegap-nfc/PhoneGapNfc-nfc-tests.ts new file mode 100644 index 000000000..e677ccdcc --- /dev/null +++ b/phonegap-nfc/PhoneGapNfc-nfc-tests.ts @@ -0,0 +1,50 @@ +/// + +nfc.addTagDiscoveredListener(() => {}); +nfc.addTagDiscoveredListener(() => {},() => {}, () => {}); + +nfc.addMimeTypeListener('text/json',() => {}); +nfc.addMimeTypeListener('text/json',() => {},() => {}, () => {}); + +nfc.addNdefListener(() => {}); +nfc.addNdefListener(() => {}, () => {},() => {}); + +nfc.addNdefFormatableListener(() => {}); +nfc.addNdefFormatableListener(() => {}, () => {}, () => {}); + +nfc.write([],() => {}, () => {}); + +nfc.makeReadOnly(); +nfc.makeReadOnly(() => {}, () => {}); + +nfc.share([]); +nfc.share([],() => {}, () => {}); + +nfc.unshare(); +nfc.unshare(() => {}, () => {}); + +nfc.handover('uri',() => {}, () => {}); +nfc.handover(['uri'],() => {}, () => {}); +nfc.handover('uri'); +nfc.handover(['uri']); + +nfc.stopHandover(); +nfc.stopHandover(() => {}, () => {}); + +nfc.erase(); +nfc.erase(() => {}, () => {}); + +nfc.enabled(); +nfc.enabled(() => {}, () => {}); + +nfc.removeTagDiscoveredListener(() => {}); +nfc.removeTagDiscoveredListener(() => {},() => {},() => {}); + +nfc.removeMimeTypeListener('text/json',() => {}); +nfc.removeMimeTypeListener('text/json',() => {},() => {},() => {}); + +nfc.removeNdefListener(() => {}); +nfc.removeNdefListener(() => {},() => {},() => {}); + +nfc.showSettings(); +nfc.showSettings(() => {},() => {}); diff --git a/phonegap-nfc/PhoneGapNfc.d.ts b/phonegap-nfc/PhoneGapNfc.d.ts new file mode 100644 index 000000000..21c7b959c --- /dev/null +++ b/phonegap-nfc/PhoneGapNfc.d.ts @@ -0,0 +1,456 @@ +// Type definitions for Phonegap NFC Plugin +// Project: https://github.com/chariotsolutions/phonegap-nfc +// Definitions by: Michael Desigaud +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Document { + addEventListener(type: 'deviceready', listener: (ev: Event) => any, useCapture?: boolean): void; +} + +/** + * Global object NFC. + */ +interface Window { + nfc: Nfc; + ndef: Ndef; + util:Util; + fireNfcTagEvent(event:TagEvent, tagAsJson:string):void; +} + +interface Tag { + id:Array; + techTypes:Array; + type:string; + date:string; +} + +interface NdefRecord { + /** + * 3-bit TNF (Type Name Format) - use one of the TNF_* constants + */ + tnf:number; + /** + * byte array, containing zero to 255 bytes, must not be null + */ + type:Array; + /** + * byte array, containing zero to 255 bytes, must not be null + */ + id:Array; + /** + * byte array, containing zero to (2 ** 32 - 1) bytes, must not be null + */ + payload:Array; +} + +interface NdefTag extends Tag { + canMakeReadOnly:boolean; + isWritable:boolean; + maxSize:number; + records:Array; +} + +interface TagEvent extends Event { + tag:Tag; +} + +interface NdefTagEvent extends TagEvent { + tag:NdefTag; +} + +interface UriHelper { + /** + * URI identifier codes from URI Record Type Definition NFCForum-TS-RTD_URI_1.0 2006-07-24 + * index in array matches code in the spec + */ + protocols:Array; + + /** + * Decode a URI payload bytes + * @param data + */ + decodePayload(data:any):string; + + /** + * shorten a URI with standard prefix + * @param uri + */ + encodePayload(uri:string):Array; +} + +interface TextHelper { + + /** + * Decode a URI payload bytes + * @param data + */ + decodePayload(data:any):string; + + /** + * Encode text payload + * @param text + * @param lang + * @param encoding + */ + encodePayload(text:string, lang:string, encoding:string):Array; +} + +/** + * The Ndef object. + */ +interface Ndef { + + TNF_EMPTY:number; + TNF_WELL_KNOWN: number; + TNF_MIME_MEDIA: number; + TNF_ABSOLUTE_URI: number; + TNF_EXTERNAL_TYPE: number; + TNF_UNKNOWN: number; + TNF_UNCHANGED: number; + TNF_RESERVED: number; + + RTD_TEXT: Array; // "T" + RTD_URI: Array; // "U" + RTD_SMART_POSTER: Array; // "Sp" + RTD_ALTERNATIVE_CARRIER: Array; // "ac" + RTD_HANDOVER_CARRIER: Array; // "Hc" + RTD_HANDOVER_REQUEST: Array; // "Hr" + RTD_HANDOVER_SELECT: Array; // "Hs" + + uriHelper:UriHelper; + textHelper:TextHelper; + /** + * Creates a JSON representation of a NdefRecord. + * + * @param tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants + * @param type array, containing zero to 255 bytes, must not be null + * @param id byte array, containing zero to 255 bytes, must not be null + * @param payload byte array, containing zero to (2 ** 32 - 1) bytes, must not be null + * + * @return NdefRecord + * + * @see Ndef.textRecord, Ndef.uriRecord and Ndef.mimeMediaRecord for examples + */ + record(tnf:number, type:Array, id:Array, payload:Array):NdefRecord; + + /** + * Helper that creates an NdefRecord containing plain text. + * + * @param text String of text to encode + * @paramlanguageCode ISO/IANA language code. Examples: “fi”, “en-US”, “fr- CA”, “jp”. (optional) + * @param id byte[] (optional) + * + * @return NdefRecord + */ + textRecord(text:string, languageCode:string, id:Array):NdefRecord; + + /** + * Helper that creates a NdefRecord containing a URI. + * + * @param uri String + * @param id byte[] (optional) + * + * @return NdefRecord + */ + uriRecord(uri:string, id:Array):NdefRecord; + + /** + * Helper that creates a NdefRecord containing an absolute URI. + * + * An Absolute URI record means the URI describes the payload of the record. + * + * For example a SOAP message could use "http://schemas.xmlsoap.org/soap/envelope/" + * as the type and XML content for the payload. + * + * Absolute URI can also be used to write LaunchApp records for Windows. + * + * See 2.4.2 Payload Type of the NDEF Specification + * http://www.nfc-forum.org/specs/spec_list#ndefts + * + * Note that by default, Android will open the URI defined in the type + * field of an Absolute URI record (TNF=3) and ignore the payload. + * BlackBerry and Windows do not open the browser for TNF=3. + * + * To write a URI as the payload use ndef.uriRecord(uri) + * + * @param uri String + * @param payload byte[] or String + * @param id byte[] (optional) + * + * @return NdefRecord + */ + absoluteUriRecord(uri:string, payload:Array, id:Array):NdefRecord; + + /** + * Helper that creates a NdefRecordcontaining an mimeMediaRecord. + * + * @param mimeType String + * @param payload byte[] + * @param id byte[] (optional) + */ + mimeMediaRecord(mimeType:string, payload:Array, id:Array):NdefRecord; + + /** + * Helper that creates an NDEF record containing an Smart Poster. + * + * @param ndefRecords array of NdefRecord + * @param id byte[] (optional) + * + * @return NdefRecord + */ + smartPoster(ndefRecords:Array, id:Array):NdefRecord; + + /** + * Helper that creates an empty NdefRecord. + * + */ + emptyRecord():NdefRecord; + + /** + * Helper that creates an Android Application Record (AAR). + * http://developer.android.com/guide/topics/connectivity/nfc/nfc.html#aar + * @param packageName android package name + * + */ + androidApplicationRecord(packageName:string):NdefRecord; + + /** + * Encodes an NDEF Message into bytes that can be written to a NFC tag. + * + * @param ndefRecords an Array of NdefRecord + * + * @return Array + * + * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/ + */ + encodeMessage(ndefRecords:Array):Array; + + /** + * Decodes an array bytes into an NDEF Message + * + * @param bytes Array read from a NFC tag + * + * @return array of NdefRecord + * + * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/ + */ + decodeMessage(bytes:Array):Array; + + /** + * Decode the bit flags from a TNF Byte. + * + * @return object with decoded data + * + * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout + */ + decodeTnf(tnf_byte:number):any; + + /** + * Encode NDEF bit flags into a TNF Byte. + * + * @return tnf byte + * + * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout + */ + encodeTnf(mb:number, me:number, cf:number, sr:number, il:number, tnf:number):number; + + /** + * Convert TNF to String for user friendly display + * + *@param tnf tnf byte + */ + tnfToString(tnf:number):string; +} + +interface Util { + /** + * Convert bytes to string + * @param bytes + */ + bytesToString(bytes:Array):string; + + /** + * Convert string to bytes + * @param string + */ + stringToBytes(string:string):Array; + + /** + * Convert bytes to hexadecimal string + * @param bytes + */ + bytesToHexString(bytes:Array):string; +} + +/** + * The Nfc object. + */ +interface Nfc extends Util { + /** + * Function nfc.addTagDiscoveredListener registers the callback for tag events. + * This event occurs when any tag is detected by the phone + * @param callback The callback that is called when a tag is detected. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addTagDiscoveredListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.addMimeTypeListener registers the callback for ndef-mime events. + * A ndef-mime event occurs when a Ndef.TNF_MIME_MEDIA tag is read and matches the specified MIME type. + * This function can be called multiple times to register different MIME types. You should use the same handler for all MIME messages. + * @param mimeType The MIME type to filter for messages. + * @param callback The callback that is called when an NDEF tag matching the MIME type is read. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addMimeTypeListener(mimeType:string, callback:() => void, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.addNdefListener registers the callback for ndef events. + * A ndef event is fired when a NDEF tag is read. + * For BlackBerry 10, you must configure the type of tags your application will read with an invoke-target in config.xml. + * On Android registered mimeTypeListeners takes precedence over this more generic NDEF listener. + * @param callback The callback that is called when an NDEF tag is read. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addNdefListener(callback:(event:NdefTagEvent) => void, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.addNdefFormatableListener registers the callback for ndef-formatable events. + * A ndef-formatable event occurs when a tag is read that can be NDEF formatted. + * This is not fired for tags that are already formatted as NDEF. + * The ndef-formatable event will not contain an NdefMessage. + * @param callback The callback that is called when NDEF formatable tag is read. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addNdefFormatableListener(callback:(event:NdefTagEvent) => void, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.write writes an NdefMessage to a NFC tag. + * On Android this method must be called from within an NDEF TagEvent Handler. + * On Windows this method may be called from within the NDEF TagEvent Handler. + * On Windows Phone 8.1 this method should be called outside the NDEF TagEvent Handler, + * otherwise Windows tries to read the tag contents as you are writing to the tag. + * @param ndefMessage An array of NDEF Records. + * @param win The callback that is called when the tag is written. + * @param fail The callback that is called if there was an error. + */ + write(ndefMessage:Array, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.makeReadOnly make a NFC tag read only. + * Warning this is permanent and can not be undone. + * On Android this method must be called from within an NDEF TagEvent Handler. + * @param win The callback that is called when the tag is locked. + * @param fail The callback that is called if there was an error. + */ + makeReadOnly(win?:() => void, fail?:() => void):void; + + /** + * Function nfc.share writes an NdefMessage via peer-to-peer. + * This should appear as an NFC tag to another device. + * @param ndefMessage An array of NDEF Records. + * @param win The callback that is called when the message is pushed. + * @param fail The callback that is called if there was an error. + */ + share(ndefMessage:Array, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.unshare stops sharing data via peer-to-peer. + * @param win The callback that is called when sharing stops. + * @param fail The callback that is called if there was an error. + */ + unshare(win?:() => void, fail?:() => void):void; + + /** + * Function nfc.handover shares files to a NFC peer using handover. Files are sent by specifying a file:// or context:// URI or a list of URIs. + * The file transfer is initiated with NFC but the transfer is completed with over Bluetooth or WiFi which is handled by a NFC handover request. + * The Android code is responsible for building the handover NFC Message. + * This is Android only, but it should be possible to add implementations for other platforms. + * @param uris A URI as a String, or an array of URIs. + * @param win The callback that is called when the message is pushed. + * @param fail The callback that is called if there was an error. + */ + handover(uris:string|Array, win?:() => void, fail?:() => void):void; + + /** + * Function nfc.stopHandover stops sharing data via peer-to-peer. + * @param win The callback that is called when sharing stops. + * @param fail The callback that is called if there was an error. + */ + stopHandover(win?:() => void, fail?:() => void):void; + + /** + * Function nfc.erase erases a tag by writing an empty message. + * Will format unformatted tags before writing. + * This method must be called from within an NDEF TagEvent Handler. + * @param win The callback that is called when sharing stops. + * @param fail The callback that is called if there was an error. + */ + erase(win?:() => void, fail?:() => void):void; + + /** + * Function nfc.enabled explicitly checks to see if the phone has NFC and if NFC is enabled. + * If everything is OK, the success callback is called. + * If there is a problem, the failure callback will be called with a reason code. + * The reason will be NO_NFC if the device doesn't support NFC and NFC_DISABLED if the user has disabled NFC. + * Note: that on Android the NFC status is checked before every API call NO_NFC or NFC_DISABLED can be returned in any failure function. + * Windows will return NO_NFC_OR_NFC_DISABLED when NFC is not present or disabled. + * If the user disabled NFC after the application started, Windows may return NFC_DISABLED. + * Windows checks the NFC status before most API calls, but there are some cases when the NFC state can not be determined. + * @param win The callback that is called when NFC is enabled. + * @param fail The callback that is called when NFC is disabled or missing. + */ + enabled(win?:() => void, fail?:() => void):void; + + /** + * Removes the previously registered event listener added via nfc.addTagDiscoveredListener + * @param callback The previously registered callback. + * @param win The callback that is called when the listener is successfully removed. + * @param fail The callback that is called if there was an error during removal. + */ + removeTagDiscoveredListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; + + /** + * Removes the previously registered event listener added via nfc.addMimeTypeListener + * @param mimeType The MIME type to filter for messages. + * @param callback The previously registered callback. + * @param win The callback that is called when the listener is successfully removed. + * @param fail The callback that is called if there was an error during removal. + */ + removeMimeTypeListener(mimeType:string, callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; + + /** + * Removes the previously registered event listener for NDEF tags added via nfc.addNdefListener. + * @param callback The previously registered callback. + * @param win The callback that is called when the listener is successfully removed. + * @param fail The callback that is called if there was an error during removal. + */ + removeNdefListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; + + /** + * Function showSettings opens the NFC settings for the operating system. + * @param win Success callback function + * @param fail Error callback function, invoked when error occurs. + */ + showSettings(win?:() => void, fail?:() => void):void; +} + +declare var ndef:Ndef; +declare var nfc:Nfc; +declare var util:Util; + + +declare module 'ndef' { + export = ndef; +} + +declare module 'nfc' { + export = nfc; +} + + + From 7d71ad4c0dc842ca0c0573483e60e972f2ec5ea4 Mon Sep 17 00:00:00 2001 From: Michael DESIGAUD Date: Wed, 24 Feb 2016 19:03:01 +0100 Subject: [PATCH 05/72] Fix typescript file name --- .../{PhoneGapNfc-ndef-tests.ts => phonegap-nfc-ndef-tests.ts} | 2 +- .../{PhoneGapNfc-nfc-tests.ts => phonegap-nfc-nfc-tests.ts} | 2 +- phonegap-nfc/{PhoneGapNfc.d.ts => phonegap-nfc.d.ts} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename phonegap-nfc/{PhoneGapNfc-ndef-tests.ts => phonegap-nfc-ndef-tests.ts} (94%) rename phonegap-nfc/{PhoneGapNfc-nfc-tests.ts => phonegap-nfc-nfc-tests.ts} (96%) rename phonegap-nfc/{PhoneGapNfc.d.ts => phonegap-nfc.d.ts} (100%) diff --git a/phonegap-nfc/PhoneGapNfc-ndef-tests.ts b/phonegap-nfc/phonegap-nfc-ndef-tests.ts similarity index 94% rename from phonegap-nfc/PhoneGapNfc-ndef-tests.ts rename to phonegap-nfc/phonegap-nfc-ndef-tests.ts index 29b8c1326..9f836c6dd 100644 --- a/phonegap-nfc/PhoneGapNfc-ndef-tests.ts +++ b/phonegap-nfc/phonegap-nfc-ndef-tests.ts @@ -1,4 +1,4 @@ -/// +/// let record:NdefRecord = ndef.record(0x01,[0x0F],[0x0C],[0xFF]); diff --git a/phonegap-nfc/PhoneGapNfc-nfc-tests.ts b/phonegap-nfc/phonegap-nfc-nfc-tests.ts similarity index 96% rename from phonegap-nfc/PhoneGapNfc-nfc-tests.ts rename to phonegap-nfc/phonegap-nfc-nfc-tests.ts index e677ccdcc..c596a99d7 100644 --- a/phonegap-nfc/PhoneGapNfc-nfc-tests.ts +++ b/phonegap-nfc/phonegap-nfc-nfc-tests.ts @@ -1,4 +1,4 @@ -/// +/// nfc.addTagDiscoveredListener(() => {}); nfc.addTagDiscoveredListener(() => {},() => {}, () => {}); diff --git a/phonegap-nfc/PhoneGapNfc.d.ts b/phonegap-nfc/phonegap-nfc.d.ts similarity index 100% rename from phonegap-nfc/PhoneGapNfc.d.ts rename to phonegap-nfc/phonegap-nfc.d.ts From bb6fa13eac14f20b1b837af83529d9cc293528ca Mon Sep 17 00:00:00 2001 From: Michael DESIGAUD Date: Fri, 26 Feb 2016 17:52:32 +0100 Subject: [PATCH 06/72] Rename test file --- phonegap-nfc/phonegap-nfc-ndef-tests.ts | 27 ------------------- ...nfc-nfc-tests.ts => phonegap-nfc.tests.ts} | 26 ++++++++++++++++++ 2 files changed, 26 insertions(+), 27 deletions(-) delete mode 100644 phonegap-nfc/phonegap-nfc-ndef-tests.ts rename phonegap-nfc/{phonegap-nfc-nfc-tests.ts => phonegap-nfc.tests.ts} (63%) diff --git a/phonegap-nfc/phonegap-nfc-ndef-tests.ts b/phonegap-nfc/phonegap-nfc-ndef-tests.ts deleted file mode 100644 index 9f836c6dd..000000000 --- a/phonegap-nfc/phonegap-nfc-ndef-tests.ts +++ /dev/null @@ -1,27 +0,0 @@ -/// - -let record:NdefRecord = ndef.record(0x01,[0x0F],[0x0C],[0xFF]); - -record = ndef.textRecord('textRecord','fr',[24,78]); - -record = ndef.uriRecord('uriRecord',[24,78]); - -record = ndef.absoluteUriRecord('uriRecord',[88,142],[24,78]); - -record = ndef.mimeMediaRecord('text/json',[88,142],[24,78]); - -record = ndef.smartPoster([],[88,142]); - -record = ndef.emptyRecord(); - -record = ndef.androidApplicationRecord('fr.redfroggy.phonegap'); - -let bytes:Array = ndef.encodeMessage([]); - -let records:Array = ndef.decodeMessage(bytes); - -let obj:any = ndef.decodeTnf(bytes[0]); - -let tnfByte:number = ndef.encodeTnf(bytes[0],bytes[1],bytes[2],bytes[3],bytes[4],bytes[5]); - -let tnfString:string = ndef.tnfToString(tnfByte); diff --git a/phonegap-nfc/phonegap-nfc-nfc-tests.ts b/phonegap-nfc/phonegap-nfc.tests.ts similarity index 63% rename from phonegap-nfc/phonegap-nfc-nfc-tests.ts rename to phonegap-nfc/phonegap-nfc.tests.ts index c596a99d7..db9fce2b5 100644 --- a/phonegap-nfc/phonegap-nfc-nfc-tests.ts +++ b/phonegap-nfc/phonegap-nfc.tests.ts @@ -48,3 +48,29 @@ nfc.removeNdefListener(() => {},() => {},() => {}); nfc.showSettings(); nfc.showSettings(() => {},() => {}); + +let record:NdefRecord = ndef.record(0x01,[0x0F],[0x0C],[0xFF]); + +record = ndef.textRecord('textRecord','fr',[24,78]); + +record = ndef.uriRecord('uriRecord',[24,78]); + +record = ndef.absoluteUriRecord('uriRecord',[88,142],[24,78]); + +record = ndef.mimeMediaRecord('text/json',[88,142],[24,78]); + +record = ndef.smartPoster([],[88,142]); + +record = ndef.emptyRecord(); + +record = ndef.androidApplicationRecord('fr.redfroggy.phonegap'); + +let bytes:Array = ndef.encodeMessage([]); + +let records:Array = ndef.decodeMessage(bytes); + +let obj:any = ndef.decodeTnf(bytes[0]); + +let tnfByte:number = ndef.encodeTnf(bytes[0],bytes[1],bytes[2],bytes[3],bytes[4],bytes[5]); + +let tnfString:string = ndef.tnfToString(tnfByte); From b4d480dde69dfdebe8c2c453d25ee924c0702dd6 Mon Sep 17 00:00:00 2001 From: Michael DESIGAUD Date: Fri, 26 Feb 2016 22:21:29 +0100 Subject: [PATCH 07/72] Fix modules --- phonegap-nfc/phonegap-nfc.d.ts | 832 +++++++++++++++-------------- phonegap-nfc/phonegap-nfc.tests.ts | 4 + 2 files changed, 422 insertions(+), 414 deletions(-) diff --git a/phonegap-nfc/phonegap-nfc.d.ts b/phonegap-nfc/phonegap-nfc.d.ts index 21c7b959c..1a6c7bfd8 100644 --- a/phonegap-nfc/phonegap-nfc.d.ts +++ b/phonegap-nfc/phonegap-nfc.d.ts @@ -7,450 +7,454 @@ interface Document { addEventListener(type: 'deviceready', listener: (ev: Event) => any, useCapture?: boolean): void; } -/** - * Global object NFC. - */ -interface Window { - nfc: Nfc; - ndef: Ndef; - util:Util; - fireNfcTagEvent(event:TagEvent, tagAsJson:string):void; -} - -interface Tag { - id:Array; - techTypes:Array; - type:string; - date:string; -} - -interface NdefRecord { - /** - * 3-bit TNF (Type Name Format) - use one of the TNF_* constants - */ - tnf:number; - /** - * byte array, containing zero to 255 bytes, must not be null - */ - type:Array; - /** - * byte array, containing zero to 255 bytes, must not be null - */ - id:Array; - /** - * byte array, containing zero to (2 ** 32 - 1) bytes, must not be null - */ - payload:Array; -} - -interface NdefTag extends Tag { - canMakeReadOnly:boolean; - isWritable:boolean; - maxSize:number; - records:Array; -} - -interface TagEvent extends Event { - tag:Tag; -} - -interface NdefTagEvent extends TagEvent { - tag:NdefTag; -} - -interface UriHelper { - /** - * URI identifier codes from URI Record Type Definition NFCForum-TS-RTD_URI_1.0 2006-07-24 - * index in array matches code in the spec - */ - protocols:Array; +declare module PhoneGapNfc { /** - * Decode a URI payload bytes - * @param data + * Global object NFC. */ - decodePayload(data:any):string; + interface Window { + nfc: Nfc; + ndef: Ndef; + util:Util; + fireNfcTagEvent(event:TagEvent, tagAsJson:string):void; + } + + interface Tag { + id:Array; + techTypes:Array; + type:string; + date:string; + } + + interface NdefRecord { + /** + * 3-bit TNF (Type Name Format) - use one of the TNF_* constants + */ + tnf:number; + /** + * byte array, containing zero to 255 bytes, must not be null + */ + type:Array; + /** + * byte array, containing zero to 255 bytes, must not be null + */ + id:Array; + /** + * byte array, containing zero to (2 ** 32 - 1) bytes, must not be null + */ + payload:Array; + } + + interface NdefTag extends Tag { + canMakeReadOnly:boolean; + isWritable:boolean; + maxSize:number; + records:Array; + } + + interface TagEvent extends Event { + tag:Tag; + } + + interface NdefTagEvent extends TagEvent { + tag:NdefTag; + } + + interface UriHelper { + /** + * URI identifier codes from URI Record Type Definition NFCForum-TS-RTD_URI_1.0 2006-07-24 + * index in array matches code in the spec + */ + protocols:Array; + + /** + * Decode a URI payload bytes + * @param data + */ + decodePayload(data:any):string; + + /** + * shorten a URI with standard prefix + * @param uri + */ + encodePayload(uri:string):Array; + } + + interface TextHelper { + + /** + * Decode a URI payload bytes + * @param data + */ + decodePayload(data:any):string; + + /** + * Encode text payload + * @param text + * @param lang + * @param encoding + */ + encodePayload(text:string, lang:string, encoding:string):Array; + } /** - * shorten a URI with standard prefix - * @param uri + * The Ndef object. */ - encodePayload(uri:string):Array; -} + interface Ndef { -interface TextHelper { + TNF_EMPTY:number; + TNF_WELL_KNOWN: number; + TNF_MIME_MEDIA: number; + TNF_ABSOLUTE_URI: number; + TNF_EXTERNAL_TYPE: number; + TNF_UNKNOWN: number; + TNF_UNCHANGED: number; + TNF_RESERVED: number; + + RTD_TEXT: Array; // "T" + RTD_URI: Array; // "U" + RTD_SMART_POSTER: Array; // "Sp" + RTD_ALTERNATIVE_CARRIER: Array; // "ac" + RTD_HANDOVER_CARRIER: Array; // "Hc" + RTD_HANDOVER_REQUEST: Array; // "Hr" + RTD_HANDOVER_SELECT: Array; // "Hs" + + uriHelper:UriHelper; + textHelper:TextHelper; + /** + * Creates a JSON representation of a NdefRecord. + * + * @param tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants + * @param type array, containing zero to 255 bytes, must not be null + * @param id byte array, containing zero to 255 bytes, must not be null + * @param payload byte array, containing zero to (2 ** 32 - 1) bytes, must not be null + * + * @return NdefRecord + * + * @see Ndef.textRecord, Ndef.uriRecord and Ndef.mimeMediaRecord for examples + */ + record(tnf:number, type:Array, id:Array, payload:Array):NdefRecord; + + /** + * Helper that creates an NdefRecord containing plain text. + * + * @param text String of text to encode + * @paramlanguageCode ISO/IANA language code. Examples: “fi”, “en-US”, “fr- CA”, “jp”. (optional) + * @param id byte[] (optional) + * + * @return NdefRecord + */ + textRecord(text:string, languageCode:string, id:Array):NdefRecord; + + /** + * Helper that creates a NdefRecord containing a URI. + * + * @param uri String + * @param id byte[] (optional) + * + * @return NdefRecord + */ + uriRecord(uri:string, id:Array):NdefRecord; + + /** + * Helper that creates a NdefRecord containing an absolute URI. + * + * An Absolute URI record means the URI describes the payload of the record. + * + * For example a SOAP message could use "http://schemas.xmlsoap.org/soap/envelope/" + * as the type and XML content for the payload. + * + * Absolute URI can also be used to write LaunchApp records for Windows. + * + * See 2.4.2 Payload Type of the NDEF Specification + * http://www.nfc-forum.org/specs/spec_list#ndefts + * + * Note that by default, Android will open the URI defined in the type + * field of an Absolute URI record (TNF=3) and ignore the payload. + * BlackBerry and Windows do not open the browser for TNF=3. + * + * To write a URI as the payload use ndef.uriRecord(uri) + * + * @param uri String + * @param payload byte[] or String + * @param id byte[] (optional) + * + * @return NdefRecord + */ + absoluteUriRecord(uri:string, payload:Array, id:Array):NdefRecord; + + /** + * Helper that creates a NdefRecordcontaining an mimeMediaRecord. + * + * @param mimeType String + * @param payload byte[] + * @param id byte[] (optional) + */ + mimeMediaRecord(mimeType:string, payload:Array, id:Array):NdefRecord; + + /** + * Helper that creates an NDEF record containing an Smart Poster. + * + * @param ndefRecords array of NdefRecord + * @param id byte[] (optional) + * + * @return NdefRecord + */ + smartPoster(ndefRecords:Array, id:Array):NdefRecord; + + /** + * Helper that creates an empty NdefRecord. + * + */ + emptyRecord():NdefRecord; + + /** + * Helper that creates an Android Application Record (AAR). + * http://developer.android.com/guide/topics/connectivity/nfc/nfc.html#aar + * @param packageName android package name + * + */ + androidApplicationRecord(packageName:string):NdefRecord; + + /** + * Encodes an NDEF Message into bytes that can be written to a NFC tag. + * + * @param ndefRecords an Array of NdefRecord + * + * @return Array + * + * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/ + */ + encodeMessage(ndefRecords:Array):Array; + + /** + * Decodes an array bytes into an NDEF Message + * + * @param bytes Array read from a NFC tag + * + * @return array of NdefRecord + * + * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/ + */ + decodeMessage(bytes:Array):Array; + + /** + * Decode the bit flags from a TNF Byte. + * + * @return object with decoded data + * + * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout + */ + decodeTnf(tnf_byte:number):any; + + /** + * Encode NDEF bit flags into a TNF Byte. + * + * @return tnf byte + * + * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout + */ + encodeTnf(mb:number, me:number, cf:number, sr:number, il:number, tnf:number):number; + + /** + * Convert TNF to String for user friendly display + * + *@param tnf tnf byte + */ + tnfToString(tnf:number):string; + } + + interface Util { + /** + * Convert bytes to string + * @param bytes + */ + bytesToString(bytes:Array):string; + + /** + * Convert string to bytes + * @param string + */ + stringToBytes(string:string):Array; + + /** + * Convert bytes to hexadecimal string + * @param bytes + */ + bytesToHexString(bytes:Array):string; + } /** - * Decode a URI payload bytes - * @param data + * The Nfc object. */ - decodePayload(data:any):string; + interface Nfc extends Util { + /** + * Function nfc.addTagDiscoveredListener registers the callback for tag events. + * This event occurs when any tag is detected by the phone + * @param callback The callback that is called when a tag is detected. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addTagDiscoveredListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - /** - * Encode text payload - * @param text - * @param lang - * @param encoding - */ - encodePayload(text:string, lang:string, encoding:string):Array; -} + /** + * Function nfc.addMimeTypeListener registers the callback for ndef-mime events. + * A ndef-mime event occurs when a Ndef.TNF_MIME_MEDIA tag is read and matches the specified MIME type. + * This function can be called multiple times to register different MIME types. You should use the same handler for all MIME messages. + * @param mimeType The MIME type to filter for messages. + * @param callback The callback that is called when an NDEF tag matching the MIME type is read. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addMimeTypeListener(mimeType:string, callback:() => void, win?:() => void, fail?:() => void):void; -/** - * The Ndef object. - */ -interface Ndef { + /** + * Function nfc.addNdefListener registers the callback for ndef events. + * A ndef event is fired when a NDEF tag is read. + * For BlackBerry 10, you must configure the type of tags your application will read with an invoke-target in config.xml. + * On Android registered mimeTypeListeners takes precedence over this more generic NDEF listener. + * @param callback The callback that is called when an NDEF tag is read. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addNdefListener(callback:(event:NdefTagEvent) => void, win?:() => void, fail?:() => void):void; - TNF_EMPTY:number; - TNF_WELL_KNOWN: number; - TNF_MIME_MEDIA: number; - TNF_ABSOLUTE_URI: number; - TNF_EXTERNAL_TYPE: number; - TNF_UNKNOWN: number; - TNF_UNCHANGED: number; - TNF_RESERVED: number; + /** + * Function nfc.addNdefFormatableListener registers the callback for ndef-formatable events. + * A ndef-formatable event occurs when a tag is read that can be NDEF formatted. + * This is not fired for tags that are already formatted as NDEF. + * The ndef-formatable event will not contain an NdefMessage. + * @param callback The callback that is called when NDEF formatable tag is read. + * @param win The callback that is called when the listener is added. + * @param fail The callback that is called if there was an error. + */ + addNdefFormatableListener(callback:(event:NdefTagEvent) => void, win?:() => void, fail?:() => void):void; - RTD_TEXT: Array; // "T" - RTD_URI: Array; // "U" - RTD_SMART_POSTER: Array; // "Sp" - RTD_ALTERNATIVE_CARRIER: Array; // "ac" - RTD_HANDOVER_CARRIER: Array; // "Hc" - RTD_HANDOVER_REQUEST: Array; // "Hr" - RTD_HANDOVER_SELECT: Array; // "Hs" + /** + * Function nfc.write writes an NdefMessage to a NFC tag. + * On Android this method must be called from within an NDEF TagEvent Handler. + * On Windows this method may be called from within the NDEF TagEvent Handler. + * On Windows Phone 8.1 this method should be called outside the NDEF TagEvent Handler, + * otherwise Windows tries to read the tag contents as you are writing to the tag. + * @param ndefMessage An array of NDEF Records. + * @param win The callback that is called when the tag is written. + * @param fail The callback that is called if there was an error. + */ + write(ndefMessage:Array, win?:() => void, fail?:() => void):void; - uriHelper:UriHelper; - textHelper:TextHelper; - /** - * Creates a JSON representation of a NdefRecord. - * - * @param tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants - * @param type array, containing zero to 255 bytes, must not be null - * @param id byte array, containing zero to 255 bytes, must not be null - * @param payload byte array, containing zero to (2 ** 32 - 1) bytes, must not be null - * - * @return NdefRecord - * - * @see Ndef.textRecord, Ndef.uriRecord and Ndef.mimeMediaRecord for examples - */ - record(tnf:number, type:Array, id:Array, payload:Array):NdefRecord; + /** + * Function nfc.makeReadOnly make a NFC tag read only. + * Warning this is permanent and can not be undone. + * On Android this method must be called from within an NDEF TagEvent Handler. + * @param win The callback that is called when the tag is locked. + * @param fail The callback that is called if there was an error. + */ + makeReadOnly(win?:() => void, fail?:() => void):void; - /** - * Helper that creates an NdefRecord containing plain text. - * - * @param text String of text to encode - * @paramlanguageCode ISO/IANA language code. Examples: “fi”, “en-US”, “fr- CA”, “jp”. (optional) - * @param id byte[] (optional) - * - * @return NdefRecord - */ - textRecord(text:string, languageCode:string, id:Array):NdefRecord; + /** + * Function nfc.share writes an NdefMessage via peer-to-peer. + * This should appear as an NFC tag to another device. + * @param ndefMessage An array of NDEF Records. + * @param win The callback that is called when the message is pushed. + * @param fail The callback that is called if there was an error. + */ + share(ndefMessage:Array, win?:() => void, fail?:() => void):void; - /** - * Helper that creates a NdefRecord containing a URI. - * - * @param uri String - * @param id byte[] (optional) - * - * @return NdefRecord - */ - uriRecord(uri:string, id:Array):NdefRecord; + /** + * Function nfc.unshare stops sharing data via peer-to-peer. + * @param win The callback that is called when sharing stops. + * @param fail The callback that is called if there was an error. + */ + unshare(win?:() => void, fail?:() => void):void; - /** - * Helper that creates a NdefRecord containing an absolute URI. - * - * An Absolute URI record means the URI describes the payload of the record. - * - * For example a SOAP message could use "http://schemas.xmlsoap.org/soap/envelope/" - * as the type and XML content for the payload. - * - * Absolute URI can also be used to write LaunchApp records for Windows. - * - * See 2.4.2 Payload Type of the NDEF Specification - * http://www.nfc-forum.org/specs/spec_list#ndefts - * - * Note that by default, Android will open the URI defined in the type - * field of an Absolute URI record (TNF=3) and ignore the payload. - * BlackBerry and Windows do not open the browser for TNF=3. - * - * To write a URI as the payload use ndef.uriRecord(uri) - * - * @param uri String - * @param payload byte[] or String - * @param id byte[] (optional) - * - * @return NdefRecord - */ - absoluteUriRecord(uri:string, payload:Array, id:Array):NdefRecord; + /** + * Function nfc.handover shares files to a NFC peer using handover. Files are sent by specifying a file:// or context:// URI or a list of URIs. + * The file transfer is initiated with NFC but the transfer is completed with over Bluetooth or WiFi which is handled by a NFC handover request. + * The Android code is responsible for building the handover NFC Message. + * This is Android only, but it should be possible to add implementations for other platforms. + * @param uris A URI as a String, or an array of URIs. + * @param win The callback that is called when the message is pushed. + * @param fail The callback that is called if there was an error. + */ + handover(uris:string|Array, win?:() => void, fail?:() => void):void; - /** - * Helper that creates a NdefRecordcontaining an mimeMediaRecord. - * - * @param mimeType String - * @param payload byte[] - * @param id byte[] (optional) - */ - mimeMediaRecord(mimeType:string, payload:Array, id:Array):NdefRecord; + /** + * Function nfc.stopHandover stops sharing data via peer-to-peer. + * @param win The callback that is called when sharing stops. + * @param fail The callback that is called if there was an error. + */ + stopHandover(win?:() => void, fail?:() => void):void; - /** - * Helper that creates an NDEF record containing an Smart Poster. - * - * @param ndefRecords array of NdefRecord - * @param id byte[] (optional) - * - * @return NdefRecord - */ - smartPoster(ndefRecords:Array, id:Array):NdefRecord; + /** + * Function nfc.erase erases a tag by writing an empty message. + * Will format unformatted tags before writing. + * This method must be called from within an NDEF TagEvent Handler. + * @param win The callback that is called when sharing stops. + * @param fail The callback that is called if there was an error. + */ + erase(win?:() => void, fail?:() => void):void; - /** - * Helper that creates an empty NdefRecord. - * - */ - emptyRecord():NdefRecord; + /** + * Function nfc.enabled explicitly checks to see if the phone has NFC and if NFC is enabled. + * If everything is OK, the success callback is called. + * If there is a problem, the failure callback will be called with a reason code. + * The reason will be NO_NFC if the device doesn't support NFC and NFC_DISABLED if the user has disabled NFC. + * Note: that on Android the NFC status is checked before every API call NO_NFC or NFC_DISABLED can be returned in any failure function. + * Windows will return NO_NFC_OR_NFC_DISABLED when NFC is not present or disabled. + * If the user disabled NFC after the application started, Windows may return NFC_DISABLED. + * Windows checks the NFC status before most API calls, but there are some cases when the NFC state can not be determined. + * @param win The callback that is called when NFC is enabled. + * @param fail The callback that is called when NFC is disabled or missing. + */ + enabled(win?:() => void, fail?:() => void):void; - /** - * Helper that creates an Android Application Record (AAR). - * http://developer.android.com/guide/topics/connectivity/nfc/nfc.html#aar - * @param packageName android package name - * - */ - androidApplicationRecord(packageName:string):NdefRecord; + /** + * Removes the previously registered event listener added via nfc.addTagDiscoveredListener + * @param callback The previously registered callback. + * @param win The callback that is called when the listener is successfully removed. + * @param fail The callback that is called if there was an error during removal. + */ + removeTagDiscoveredListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - /** - * Encodes an NDEF Message into bytes that can be written to a NFC tag. - * - * @param ndefRecords an Array of NdefRecord - * - * @return Array - * - * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/ - */ - encodeMessage(ndefRecords:Array):Array; + /** + * Removes the previously registered event listener added via nfc.addMimeTypeListener + * @param mimeType The MIME type to filter for messages. + * @param callback The previously registered callback. + * @param win The callback that is called when the listener is successfully removed. + * @param fail The callback that is called if there was an error during removal. + */ + removeMimeTypeListener(mimeType:string, callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - /** - * Decodes an array bytes into an NDEF Message - * - * @param bytes Array read from a NFC tag - * - * @return array of NdefRecord - * - * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/ - */ - decodeMessage(bytes:Array):Array; + /** + * Removes the previously registered event listener for NDEF tags added via nfc.addNdefListener. + * @param callback The previously registered callback. + * @param win The callback that is called when the listener is successfully removed. + * @param fail The callback that is called if there was an error during removal. + */ + removeNdefListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - /** - * Decode the bit flags from a TNF Byte. - * - * @return object with decoded data - * - * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout - */ - decodeTnf(tnf_byte:number):any; - - /** - * Encode NDEF bit flags into a TNF Byte. - * - * @return tnf byte - * - * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout - */ - encodeTnf(mb:number, me:number, cf:number, sr:number, il:number, tnf:number):number; - - /** - * Convert TNF to String for user friendly display - * - *@param tnf tnf byte - */ - tnfToString(tnf:number):string; -} - -interface Util { - /** - * Convert bytes to string - * @param bytes - */ - bytesToString(bytes:Array):string; - - /** - * Convert string to bytes - * @param string - */ - stringToBytes(string:string):Array; - - /** - * Convert bytes to hexadecimal string - * @param bytes - */ - bytesToHexString(bytes:Array):string; -} - -/** - * The Nfc object. - */ -interface Nfc extends Util { - /** - * Function nfc.addTagDiscoveredListener registers the callback for tag events. - * This event occurs when any tag is detected by the phone - * @param callback The callback that is called when a tag is detected. - * @param win The callback that is called when the listener is added. - * @param fail The callback that is called if there was an error. - */ - addTagDiscoveredListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.addMimeTypeListener registers the callback for ndef-mime events. - * A ndef-mime event occurs when a Ndef.TNF_MIME_MEDIA tag is read and matches the specified MIME type. - * This function can be called multiple times to register different MIME types. You should use the same handler for all MIME messages. - * @param mimeType The MIME type to filter for messages. - * @param callback The callback that is called when an NDEF tag matching the MIME type is read. - * @param win The callback that is called when the listener is added. - * @param fail The callback that is called if there was an error. - */ - addMimeTypeListener(mimeType:string, callback:() => void, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.addNdefListener registers the callback for ndef events. - * A ndef event is fired when a NDEF tag is read. - * For BlackBerry 10, you must configure the type of tags your application will read with an invoke-target in config.xml. - * On Android registered mimeTypeListeners takes precedence over this more generic NDEF listener. - * @param callback The callback that is called when an NDEF tag is read. - * @param win The callback that is called when the listener is added. - * @param fail The callback that is called if there was an error. - */ - addNdefListener(callback:(event:NdefTagEvent) => void, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.addNdefFormatableListener registers the callback for ndef-formatable events. - * A ndef-formatable event occurs when a tag is read that can be NDEF formatted. - * This is not fired for tags that are already formatted as NDEF. - * The ndef-formatable event will not contain an NdefMessage. - * @param callback The callback that is called when NDEF formatable tag is read. - * @param win The callback that is called when the listener is added. - * @param fail The callback that is called if there was an error. - */ - addNdefFormatableListener(callback:(event:NdefTagEvent) => void, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.write writes an NdefMessage to a NFC tag. - * On Android this method must be called from within an NDEF TagEvent Handler. - * On Windows this method may be called from within the NDEF TagEvent Handler. - * On Windows Phone 8.1 this method should be called outside the NDEF TagEvent Handler, - * otherwise Windows tries to read the tag contents as you are writing to the tag. - * @param ndefMessage An array of NDEF Records. - * @param win The callback that is called when the tag is written. - * @param fail The callback that is called if there was an error. - */ - write(ndefMessage:Array, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.makeReadOnly make a NFC tag read only. - * Warning this is permanent and can not be undone. - * On Android this method must be called from within an NDEF TagEvent Handler. - * @param win The callback that is called when the tag is locked. - * @param fail The callback that is called if there was an error. - */ - makeReadOnly(win?:() => void, fail?:() => void):void; - - /** - * Function nfc.share writes an NdefMessage via peer-to-peer. - * This should appear as an NFC tag to another device. - * @param ndefMessage An array of NDEF Records. - * @param win The callback that is called when the message is pushed. - * @param fail The callback that is called if there was an error. - */ - share(ndefMessage:Array, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.unshare stops sharing data via peer-to-peer. - * @param win The callback that is called when sharing stops. - * @param fail The callback that is called if there was an error. - */ - unshare(win?:() => void, fail?:() => void):void; - - /** - * Function nfc.handover shares files to a NFC peer using handover. Files are sent by specifying a file:// or context:// URI or a list of URIs. - * The file transfer is initiated with NFC but the transfer is completed with over Bluetooth or WiFi which is handled by a NFC handover request. - * The Android code is responsible for building the handover NFC Message. - * This is Android only, but it should be possible to add implementations for other platforms. - * @param uris A URI as a String, or an array of URIs. - * @param win The callback that is called when the message is pushed. - * @param fail The callback that is called if there was an error. - */ - handover(uris:string|Array, win?:() => void, fail?:() => void):void; - - /** - * Function nfc.stopHandover stops sharing data via peer-to-peer. - * @param win The callback that is called when sharing stops. - * @param fail The callback that is called if there was an error. - */ - stopHandover(win?:() => void, fail?:() => void):void; - - /** - * Function nfc.erase erases a tag by writing an empty message. - * Will format unformatted tags before writing. - * This method must be called from within an NDEF TagEvent Handler. - * @param win The callback that is called when sharing stops. - * @param fail The callback that is called if there was an error. - */ - erase(win?:() => void, fail?:() => void):void; - - /** - * Function nfc.enabled explicitly checks to see if the phone has NFC and if NFC is enabled. - * If everything is OK, the success callback is called. - * If there is a problem, the failure callback will be called with a reason code. - * The reason will be NO_NFC if the device doesn't support NFC and NFC_DISABLED if the user has disabled NFC. - * Note: that on Android the NFC status is checked before every API call NO_NFC or NFC_DISABLED can be returned in any failure function. - * Windows will return NO_NFC_OR_NFC_DISABLED when NFC is not present or disabled. - * If the user disabled NFC after the application started, Windows may return NFC_DISABLED. - * Windows checks the NFC status before most API calls, but there are some cases when the NFC state can not be determined. - * @param win The callback that is called when NFC is enabled. - * @param fail The callback that is called when NFC is disabled or missing. - */ - enabled(win?:() => void, fail?:() => void):void; - - /** - * Removes the previously registered event listener added via nfc.addTagDiscoveredListener - * @param callback The previously registered callback. - * @param win The callback that is called when the listener is successfully removed. - * @param fail The callback that is called if there was an error during removal. - */ - removeTagDiscoveredListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - - /** - * Removes the previously registered event listener added via nfc.addMimeTypeListener - * @param mimeType The MIME type to filter for messages. - * @param callback The previously registered callback. - * @param win The callback that is called when the listener is successfully removed. - * @param fail The callback that is called if there was an error during removal. - */ - removeMimeTypeListener(mimeType:string, callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - - /** - * Removes the previously registered event listener for NDEF tags added via nfc.addNdefListener. - * @param callback The previously registered callback. - * @param win The callback that is called when the listener is successfully removed. - * @param fail The callback that is called if there was an error during removal. - */ - removeNdefListener(callback:(event:TagEvent) => void, win?:() => void, fail?:() => void):void; - - /** - * Function showSettings opens the NFC settings for the operating system. - * @param win Success callback function - * @param fail Error callback function, invoked when error occurs. - */ - showSettings(win?:() => void, fail?:() => void):void; -} - -declare var ndef:Ndef; -declare var nfc:Nfc; -declare var util:Util; - - -declare module 'ndef' { - export = ndef; + /** + * Function showSettings opens the NFC settings for the operating system. + * @param win Success callback function + * @param fail Error callback function, invoked when error occurs. + */ + showSettings(win?:() => void, fail?:() => void):void; + } } declare module 'nfc' { + var nfc:PhoneGapNfc.Nfc; export = nfc; } +declare module 'ndef' { + var ndef:PhoneGapNfc.Ndef; + export = ndef; +} + +declare module 'util' { + var util:PhoneGapNfc.Util; + export = util; +} diff --git a/phonegap-nfc/phonegap-nfc.tests.ts b/phonegap-nfc/phonegap-nfc.tests.ts index db9fce2b5..ddaabebce 100644 --- a/phonegap-nfc/phonegap-nfc.tests.ts +++ b/phonegap-nfc/phonegap-nfc.tests.ts @@ -1,5 +1,9 @@ /// +import nfc = require('nfc'); +import ndef = require('ndef'); +import NdefRecord = PhoneGapNfc.NdefRecord; + nfc.addTagDiscoveredListener(() => {}); nfc.addTagDiscoveredListener(() => {},() => {}, () => {}); From 206c964ed1f68ec1778c029123dada84f2aa25c1 Mon Sep 17 00:00:00 2001 From: "Ciuca, Alexandru" Date: Wed, 2 Mar 2016 19:41:29 +0200 Subject: [PATCH 08/72] react-redux: stricter typing of connect --- react-redux/react-redux-tests.tsx | 9 +---- react-redux/react-redux.d.ts | 64 ++++++++++++++++++++++--------- 2 files changed, 47 insertions(+), 26 deletions(-) diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index 3254e6ec7..9528a7aca 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -94,6 +94,7 @@ interface TodoProps { } interface DispatchProps { addTodo(userId: number, text: string): void; + action: Function; } declare var actionCreators: () => { action: Function; @@ -270,11 +271,3 @@ let anElement: ReactElement; class NonComponent {} // this doesn't compile //connect()(NonComponent); - -// connect()(SomeClass) has the same constructor as SomeClass itself -class SomeClass extends Component { - constructor(public foo: string) { super() } - public bar: number; -} -let bar: number = new (connect()(SomeClass))("foo").bar; - diff --git a/react-redux/react-redux.d.ts b/react-redux/react-redux.d.ts index 767b6b109..a052daada 100644 --- a/react-redux/react-redux.d.ts +++ b/react-redux/react-redux.d.ts @@ -7,40 +7,68 @@ /// declare module "react-redux" { - import { Component } from 'react'; + import { Component, ComponentClass, Props, ReactNode } from 'react'; import { Store, Dispatch, ActionCreator } from 'redux'; - export class ElementClass extends Component { } - export interface ClassDecorator { - (component: T): T + /** Generic decorator, that receives T = original props, U = own props */ + interface ComponentDecorator, U extends Props> { + (component: ComponentClass): ComponentClass; + } + + /** + * Decorator that infers the type from the original component + * + * Can't use the above decorator because it would default the type to {} + */ + export interface InferableComponentDecorator { +

(component: ComponentClass

): ComponentClass

; } /** * Connects a React component to a Redux store. + * + * - Without arguments, just wraps the component, without changing the behavior / props + * + * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior + * is to override ownProps (as stated in the docs), so what remains is everything that's + * not a state or dispatch prop + * + * - When 3rd param is passed, we don't know if ownProps propagate and whether they + * should be valid component props, because it depends on mergeProps implementation. + * As such, it is the user's responsability to extend ownProps interface from state or + * dispatch props or both when applicable + * * @param mapStateToProps * @param mapDispatchToProps * @param mergeProps * @param options - */ - export function connect(mapStateToProps?: MapStateToProps, - mapDispatchToProps?: MapDispatchToPropsFunction|MapDispatchToPropsObject, - mergeProps?: MergeProps, - options?: Options): ClassDecorator; + */ + export function connect(): InferableComponentDecorator; + export function connect, U extends Props, V extends Props>( + mapStateToProps: MapStateToProps, + mapDispatchToProps?: MapDispatchToPropsFunction|MapDispatchToPropsObject + ): ComponentDecorator; + export function connect, U extends Props, V extends Props>( + mapStateToProps: MapStateToProps, + mapDispatchToProps: MapDispatchToPropsFunction|MapDispatchToPropsObject, + mergeProps: MergeProps, + options?: Options + ): ComponentDecorator; - interface MapStateToProps { - (state: any, ownProps?: any): any; + interface MapStateToProps { + (state: any, ownProps?: V): T; } - interface MapDispatchToPropsFunction { - (dispatch: Dispatch, ownProps?: any): any; + interface MapDispatchToPropsFunction { + (dispatch: Dispatch, ownProps?: V): U; } interface MapDispatchToPropsObject { [name: string]: ActionCreator; } - interface MergeProps { - (stateProps: any, dispatchProps: any, ownProps: any): any; + interface MergeProps { + (stateProps: T, dispatchProps: U, ownProps: V): T & U; } interface Options { @@ -54,16 +82,16 @@ declare module "react-redux" { pure: boolean; } - export interface Property { + export interface ProviderProps extends Props { /** * The single Redux store in your application. */ store?: Store; - children?: Function; + children?: ReactNode; } /** * Makes the Redux store available to the connect() calls in the component hierarchy below. */ - export class Provider extends Component { } + export class Provider extends Component { } } From 7c04277f862827b776c586408f49c053a8d229f9 Mon Sep 17 00:00:00 2001 From: ben-hunter-hansen Date: Thu, 3 Mar 2016 13:09:43 -0600 Subject: [PATCH 09/72] Added faceIndex property to interface THREE.Intersection --- threejs/three.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index c369e0d2b..3be13c220 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1633,6 +1633,7 @@ declare module THREE { distance: number; point: Vector3; face: Face3; + faceIndex: number; object: Object3D; } From dd3f8aedb2c354d03017c9f8b4b74ad7e02a6e8c Mon Sep 17 00:00:00 2001 From: Aluan Haddad Date: Fri, 4 Mar 2016 00:20:34 -0500 Subject: [PATCH 10/72] Changed model from (string | Object) to (string | { [key: string]: any; }) Changed the type of the model properties of various interfaces from (string | Object) to (string | { [key: string]: any; }). This change is to improve usability. While (string | Object) is correct and corresponds literally to the angular-formly docs, it does not allow for meaningful use without type casts. Also corrected some formatting to match the prevailing style used in the file. --- angular-formly/angular-formly.d.ts | 40 +++++++++++++++++------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 967a16d10..50a71c125 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -16,32 +16,34 @@ declare module 'angular-formly' { declare module AngularFormly { - interface IFieldArray extends Array { + interface IFieldArray extends Array { - } + } interface IFieldGroup { data?: { - [key: string]: any; - }; + [key: string]: any; + }; className?: string; elementAttributes?: string; - fieldGroup?: IFieldArray; + fieldGroup?: IFieldArray; form?: Object; hide?: boolean; hideExpression?: string | IExpressionFunction; key?: string | number; - model?: string | Object; - options?: IFormOptionsAPI; - templateOptions?: ITemplateOptions; - wrapper?: string | string[]; + model?: string | { + [key: string]: any; + }; + options?: IFormOptionsAPI; + templateOptions?: ITemplateOptions; + wrapper?: string | string[]; } interface IFormOptionsAPI { data?: { - [key: string]: any; - }; + [key: string]: any; + }; fieldTransform?: Function; formState?: Object; removeChromeAutoComplete?: boolean; @@ -182,8 +184,8 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#data-object */ data?: { - [key: string]: any; - }; + [key: string]: any; + }; /** @@ -287,7 +289,9 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string */ - model?: Object | string; + model?: string | { + [key: string]: any; + }; /** @@ -543,8 +547,8 @@ declare module AngularFormly { defaultOptions?: IFieldConfigurationObject | Function; controller?: Function | string | any[]; data?: { - [key: string]: any; - }; + [key: string]: any; + }; extends?: string; link?: ng.IDirectiveLinkFn; overwriteOk?: boolean; @@ -612,7 +616,9 @@ declare module AngularFormly { //The index of the field the form is on (in ng-repeat) index: number; //the model of the form (or the model specified by the field if it was specified). - model: Object | string; + model?: string | { + [key: string]: any; + }; //Shortcut to options.validation.errorExistsAndShouldBeVisible showError: boolean; //Shortcut to options.templateOptions From 58494c4205ffa4d4a61fdbc7a6f9f05324034c1f Mon Sep 17 00:00:00 2001 From: katonap Date: Fri, 4 Mar 2016 11:24:37 +0100 Subject: [PATCH 11/72] eonasdan bootstrap-datetimepicker: updated to v4.17.37 kept previous typings (v3.0.0) --- .../bootstrap.v3.datetimepicker-3.0.0.d.ts | 113 ++++ .../bootstrap.v3.datetimepicker-tests.ts | 6 - .../bootstrap.v3.datetimepicker.d.ts | 633 +++++++++++++++--- 3 files changed, 667 insertions(+), 85 deletions(-) create mode 100644 bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts new file mode 100644 index 000000000..1512f719b --- /dev/null +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts @@ -0,0 +1,113 @@ +// Type definitions for Bootstrap datetimepicker v3 +// Project: http://eonasdan.github.io/bootstrap-datetimepicker +// Definitions by: Jesica N. Fera +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * bootstrap-datetimepicker.js 3.0.0 Copyright (c) 2014 Jonathan Peterson + * Available via the MIT license. + * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. + */ + +/// +/// + +declare module BootstrapV3DatetimePicker { + interface DatetimepickerChangeEventObject extends DatetimepickerEventObject { + oldDate: moment.Moment; + } + + interface DatetimepickerEventObject extends JQueryEventObject { + date: moment.Moment; + } + + interface DatetimepickerIcons { + time?: string; + date?: string; + up?: string; + down?: string; + } + + interface DatetimepickerOptions { + pickDate?: boolean; + pickTime?: boolean; + useMinutes?: boolean; + useSeconds?: boolean; + useCurrent?: boolean; + minuteStepping?: number; + minDate?: moment.Moment | Date | string; + maxDate?: moment.Moment | Date | string; + showToday?: boolean; + collapse?: boolean; + language?: string; + defaultDate?: moment.Moment | Date | string; + disabledDates?: Array; + enabledDates?: Array; + icons?: DatetimepickerIcons; + useStrict?: boolean; + direction?: string; + sideBySide?: boolean; + daysOfWeekDisabled?: Array; + calendarWeeks?: boolean; + format?: string | boolean; + locale?: string; + showTodayButton?: boolean; + viewMode?: string; + inline?: boolean; + toolbarPlacement?: string; + showClear?: boolean; + ignoreReadonly?: boolean; + } + + interface Datetimepicker { + date(date: moment.Moment | Date | string): void; + date(): moment.Moment; + minDate(date: moment.Moment | Date | string): void; + minDate(): moment.Moment | boolean; + maxDate(date: moment.Moment | Date | string): void; + maxDate(): moment.Moment | boolean; + show(): void; + disable(): void; + enable(): void; + destroy(): void; + toggle(): void; + } + +} + + +interface JQuery { + + datetimepicker(): JQuery; + datetimepicker(options: BootstrapV3DatetimePicker.DatetimepickerOptions): JQuery; + + off(events: "dp.change", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + off(events: "dp.change", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + + on(events: "dp.change", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + on(events: "dp.change", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + on(events: 'dp.change', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + + off(events: "dp.show", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.show", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.show", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.show", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.show', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + off(events: "dp.hide", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.hide", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.hide", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.hide', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + off(events: "dp.error", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.error", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.error", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.error", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.error', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + + data(key: 'DateTimePicker'): BootstrapV3DatetimePicker.Datetimepicker; +} diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts index e17b7b10c..137e84720 100644 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts @@ -3,12 +3,6 @@ function test_cases() { $('#datetimepicker').datetimepicker(); - $('#datetimepicker').datetimepicker({ - pickDate: false - }); - $('#datetimepicker').datetimepicker({ - pickTime: false - }); $('#datetimepicker').datetimepicker({ minDate: '2012-12-31' }); diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts index eced1096f..a417f1a5b 100644 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts @@ -1,10 +1,11 @@ -// Type definitions for Bootstrap datetimepicker v3 +// Type definitions for Bootstrap 3 Datepicker v4.17.37 // Project: http://eonasdan.github.io/bootstrap-datetimepicker -// Definitions by: Jesica N. Fera +// Definitions by: Katona Péter // Definitions: https://github.com/borisyankov/DefinitelyTyped +// based on the previous version created by Jesica N. Fera /** - * bootstrap-datetimepicker.js 3.0.0 Copyright (c) 2014 Jonathan Peterson + * bootstrap-datetimepicker.js 4.17.37 Copyright (c) 2015 Jonathan Peterson * Available via the MIT license. * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. */ @@ -13,101 +14,575 @@ /// declare module BootstrapV3DatetimePicker { - interface DatetimepickerChangeEventObject extends DatetimepickerEventObject { - oldDate: moment.Moment; + + interface Datetimepicker { + /**Clears the datepicker by setting the value to null */ + clear(): void; + /**Returns the component's model current date, a moment object or null if not set. */ + date(): moment.Moment; + /**Takes string, Date, moment, null parameter and sets the components model current moment to it. + * Passing a null value unsets the components model current moment. + * Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. + * Throws: + * - TypeError - in case the newDate cannot be parsed + * + * Emits: + * - dp.change - In case newDate is different from current moment + */ + date(date: moment.Moment | Date | string): void; + /**Destroys the widget and removes all attached event listeners */ + destroy(): void; + /**Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. If the widget was visible before that call it is hidden. + * Emits: + * - dp.hide - if the widget was visible before that call + */ + disable(): void; + /**Enables the input element, the component is attached to, by removing disabled attribute from it. */ + enable(): void; + /**Hides the widget + * Emits: + * - dp.hide - if the widget was visible before that call + */ + hide(): void; + /**Returns the components current options object. + * Note that the changing the values of the returned object does not change the components actual configuration. */ + options(): DatetimepickerOptions + /**Takes an object variable with option key:value properties and configures the component. Use this to update multiple options on the component. */ + options(options: DatetimepickerOptions): void + /**Shows the widget + * Emits: + * - dp.show - if the widget was hidden before that call + * - dp.change - if the widget is opened for the first time and the useCurrent is set to true or to a granularity value and the input element the component is attached to has an empty value + */ + show(): void; + /**Shows or hides the widget + * Emits: + * - dp.hide - if the widget is hidden after the toggle call + * - dp.show - if the widget is show after the toggle call + * - dp.change - if the widget is opened for the first time and the input element is empty and options.useCurrent != false + */ + toggle(): void; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + //// Below are the getters/setters for the properties of the 'options(): DatetimepickerOptions' //// + //////////////////////////////////////////////////////////////////////////////////////////////////// + + /**Returns the options.allowInputToggle option. */ + allowInputToggle(): boolean; + /**If true, the picker will show on textbox focus and icon click when used in a button group */ + allowInputToggle(value: boolean): void; + /**Returns the current options.calendarWeeks option configuration */ + calendarWeeks(): boolean; + /**Set if the week numbers will appear to the left on the days view */ + calendarWeeks(value: boolean): void; + /**Returns the options.collapse option configuration */ + collapse(): boolean; + /**If set to false the picker will display similar to sideBySide except vertical. */ + collapse(value: boolean): void; + /**Returns the options.daysOfWeekDisabled configuration + * IMPORTANT! Throws exception if not set explicitly https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1459 + */ + daysOfWeekDisabled(): Array; + /**Takes an [ Number:0 to 6 ] and disallow the user to select weekdays that exist in this array. + * This has lower priority over the options.minDate, options.maxDate, options.disabledDates and options.enabledDates configuration settings. + * Emits: + * - dp.change - if the currently selected moment falls in the values passed on the daysOfWeek parameter. + * - dp.error - if the currently selected moment falls in the values passed on the daysOfWeek parameter. + */ + daysOfWeekDisabled(days: Array): void; + /**Returns the options.dayViewHeaderFormat option. */ + dayViewHeaderFormat(): string; + /**Used to customize the header of the day view. */ + dayViewHeaderFormat(value: string): void; + /**Returns a moment with the options.defaultDate option configuration or false if not set */ + defaultDate(): moment.Moment | boolean; + /**Will set the picker's inital date. + * If a boolean:false value is passed the options.defaultDate parameter is cleared. + * Throws: + * - TypeError - if the provided date doesn't pass validation, including disabledDates, enabledDates, minDate, maxDate, and daysOfWeekDisabled + * - TypeError - if the provided date cannot be parsed by momentjs + */ + defaultDate(date: string | Date | moment.Moment | boolean): void; + /**Returns the options.disabledDates option. + * NOTES: probably should be: disabledDates(): boolean | Array; see: DatetimepickerOptions + */ + disabledDates(): boolean | any; + /**Takes an array of values and disallows the user to select those days. + * Setting this takes precedence over options.minDate, options.maxDate configuration. + * Also calling this function removes the configuration of options.enabledDates if such exist. + * Note: These values are matched with Day granularity. + */ + disabledDates(dates: boolean | Array): void; + /**Returns the options.disabledHours option. + * NOTES: probably should be: disabledHours(): boolean | Array; see: DatetimepickerOptions + */ + disabledHours(): boolean | any; + /**Must be in 24 hour format. Will disallow hour selections (much like disabledTimeIntervals) but will affect all days. + * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ + disabledHours(value: boolean | Array): void; + /**Returns the options.disabledTimeIntervals option, or... not exactly + * IMPORTANT! Creates an object from the options.disabledTimeIntervals with the keys being numbers, the values being the moment arrays. + * eg { "0": [, ], "1": [...] } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1498 + */ + disabledTimeIntervals(): boolean | Array>; + /**Disables time selection between the given moments + * eg: [[moment({ h: 0 }), moment({ h: 8 })], [moment({ h: 18 }), moment({ h: 24 })]] + */ + disabledTimeIntervals(value: boolean | Array>): void; + /**Returns the options.enabledDates option + * NOTES: probably should be: enabledDates(): boolean | Array; see: DatetimepickerOptions + */ + enabledDates(): boolean | any; + /**Takes an array of values and allows the user to select only from those days. + * Setting this takes precedence over options.minDate, options.maxDate configuration. + * Also calling this function removes the configuration of options.disabledDates if such exist. + * Note: These values are matched with Day granularity. + */ + enabledDates(dates: boolean | Array): void; + /**Returns the options.enabledHours option. + * NOTES: probably should be: enabledHours(): boolean | Array; see: DatetimepickerOptions + */ + enabledHours(): boolean | any; + /**Must be in 24 hour format. Will allow hour selections (much like enabledTimeIntervals) but will affect all days. + * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ + enabledHours(value: boolean | Array): void; + /**Returns a boolean or array with the options.extraFormats option configuration */ + extraFormats(): boolean | Array; + /**Takes an array of valid input moment format options, or boolean:false */ + extraFormats(formats: boolean | Array): void; + /**Returns the options.focusOnShow option. */ + focusOnShow(): boolean; + /**If false, the textbox will not be given focus when the picker is shown */ + focusOnShow(value: boolean): void; + /**Returns the component's options.format string */ + format(): boolean | string; + /**Takes a moment.js format string and sets the components options.format. + * This is used for displaying and also for parsing input strings either from the input element the component is attached to or the date() function. + * The parameter can also be a boolean:false in which case the format is set to the locale's L LT. + * Note: this is also used to determine if the TimePicker sub component will display the hours in 12 or 24 format. (if "a" or "h" exists in the passed string then a 12 hour mode is set) + */ + format(format: boolean | string): void; + /**Returns options.icons */ + icons(): Icons; + /**Takes an Object of strings. + * Throws: + * - TypeError - if icons parameter is not an Object + */ + icons(icons: Icons): void; + /**Returns the options.ignoreReadonly option. */ + ignoreReadonly(): boolean; + /**Set this to true to allow the picker to be used even if the input field is readonly. This will not bypass the disabled property */ + ignoreReadonly(value: boolean): void; + /**Returns the options.inline option. */ + inline(): boolean; + /**Used to customize the header of the day view. */ + inline(value: boolean): void; + /**Returns the options.keepInvalid option. */ + keepInvalid(): boolean; + /**If true, invalid dates will not be reverted to a previous selection or changed. */ + keepInvalid(value: boolean): void; + /**Returns a string variable with the currently set options.keyBinds option. */ + keyBinds(): any; + /**Allows for several keyBinding functions to be specified for ease of access or accessibility. For defaults see {@link http://eonasdan.github.io/bootstrap-datetimepicker/Options/#keybinds}. + */ + keyBinds(value: any): void; + /**Returns the currently set locale of the options.locale */ + locale(): string; + /**Takes a string of any valid moment locale e.g. de for German. + * Throws: + * - TypeError - if the locale is not loaded via a separate script or moment-with-locale + */ + locale(newLocale: string): void; + /**Returns the currently set moment of the options.maxDate or false if not set */ + maxDate(): moment.Moment | boolean; + /**Takes a parameter and disallows the user to select a moment that is after that moment. + * If a boolean:false value is passed options.maxDate is cleared and there is no restriction to the maximum moment the user can select. + * Note: If the parameter is before the currently selected moment the currently selected moment changes to maxDate + * Throws: + * - TypeError - if the parameter cannot be parsed using the options.format and options.useStrict configuration settings + * - TypeError - if the parameter is before options.minDate + * + * Emits: + * - dp.change - if the new maxDate is after currently selected moment + * - dp.error - if the new maxDate is after currently selected moment + */ + maxDate(date: moment.Moment | Date | string | boolean): void; + /**Returns the currently set moment of the options.minDate or false if not set */ + minDate(): moment.Moment | boolean; + /**Takes a parameter and disallows the user to select a moment that is before that moment. + * If a boolean:false value is passed the options.minDate parameter is cleared and there is no restriction to the miminum moment the user can select. + * Note: If the parameter is after the currently selected moment the currently selected moment changes to minDate parameter + * Throws: + * - TypeError - if the parameter cannot be parsed using the options.format and options.useStrict configuration settings + * - TypeError - if the parameter is after options.maxDate + * + * Emits: + * - dp.change - if the new minDate is after currently selected moment + * - dp.error - if the new minDate is after currently selected moment + */ + minDate(date: moment.Moment | Date | string | boolean): void; + /**Returns the options.parseInputDate option */ + parseInputDate(): Function; + /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". + * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} + */ + parseInputDate(value: (input: string) => moment.Moment): void; + /**Returns the options.showClear option. */ + showClear(): boolean; + /**Set if the clear date button will appear on the widget */ + showClear(value: boolean): void; + /**Returns the options.showClose option. */ + showClose(): boolean; + /**If true, an icon will be displayed on the toolbar that will hide the picker */ + showClose(value: boolean): void; + /**Returns the options.showTodayButton option. */ + showTodayButton(): boolean; + /**Set if the Today button will appear on the widget */ + showTodayButton(value: boolean): void; + /**Returns a boolean of the options.sideBySide. */ + sideBySide(): boolean; + /**If sideBySide is true and the time picker is used, both components will display side by side instead of collapsing. */ + sideBySide(value: boolean): void; + /**Returns a number with the options.stepping option configuration */ + stepping(): number; + /**This will be the amount the up/down arrows move the minute value with a time picker. */ + stepping(step: number): void; + /**Returns the options.toolbarplacement option. */ + toolbarPlacement(): string; + /**Changes the placement of the toolbar where the today, clear, component switch icon are located. + * See valid values at DatetimepickerOptions.toolbarplacement + * Throws: + * - TypeError if the parameter is not a valid value + */ + toolbarPlacement(value: string): void; + /**Returns the options.tooltips option */ + tooltips(): Tooltips; + /**Sets the tooltips for icons. + * Throws: + * - TypeError - if tooltips parameter is not an Object + */ + tooltips(value: Tooltips): void; + /**Returns the options.useCurrent option configuration */ + useCurrent(): boolean | string; + /**Takes a boolean or string. + * If a boolean true is passed and the components model moment is not set (either through setDate or through a valid value on the input element the component is attached to) then the first time the user opens the datetimepicker widget the value is initialized to the current moment of the action. + * If a false boolean is passed then no initialization happens on the input element. + * You can select the granularity on the initialized moment by passing one of the following strings ("year", "month", "day", "hour", "minute") in the variable. + * If for example you pass "day" to the useCurrent function and the input field is empty the first time the user opens the datetimepicker widget the input text will be initialized to the current datetime with day granularity (ie if currentTime = 2014-08-10 13:32:33 the input value will be initialized to 2014-08-10 00:00:00) + * Note: If the options.defaultDate is set or the input element the component is attached to has already a value that takes precedence and the functionality of useCurrent is not triggered! + */ + useCurrent(value: boolean | string): void; + /**Returns the options.useStrict */ + useStrict(): boolean; + /**If useStrict is true, momentjs parsing rules will be stricter when determining if a date is valid or not. */ + useStrict(value: boolean): void; + /**Returns the options.viewDate option. */ + viewDate(): boolean | moment.Moment; + /**This will change the viewDate without changing or setting the selected date. */ + viewDate(value: string | Date | moment.Moment | boolean): void; + /**Returns the options.viewMode. */ + viewMode(): string; + /**Takes a string. See valid values at DatetimepickerOptions.viewMode + * Throws: + * - TypeError - if the parameter is not a string or not a valid value + */ + viewMode(value: string): void; + /**Returns the options.widgetPositioning object */ + widgetPositioning(): WidgetPositioningOptions; + /**WidgetPositioning defines where the dropdown with the widget will appear relative to the input element the component is attached to. + * "auto" is the default value for both horizontal and vertical keys and it tries to automatically place the dropdown in a position that is visible to the user. + * Usually you should not override those options unless you have a special need in your layout. + */ + widgetPositioning(value: WidgetPositioningOptions): void; + } + + interface DatetimepickerOptions { + /**If true, the picker will show on textbox focus and icon click when used in a button group + * @default: false + */ + allowInputToggle?: boolean; + /**Shows the week of the year to the left of first day of the week. + * @default: false + */ + calendarWeeks?: boolean; + /**Using a Bootstraps collapse to switch between date/time pickers. + * @default: true + */ + collapse?: boolean; + /**Disables the section of days of the week, e.g. weekends. + * Accepts: array of numbers from 0-6 + * @default: false + */ + daysOfWeekDisabled?: Array | boolean; + /**Changes the heading of the datepicker when in "days" view. + * @default: "MMMM YYYY" + */ + dayViewHeaderFormat?: string; + /**Will cause the date picker to stay open after a blur event. + * @default: false + */ + debug?: boolean; + /**Sets the picker default date/time. Overrides useCurrent + * @default: false + */ + defaultDate?: boolean | moment.Moment | Date | string; + /**Disables selection of dates in the array, e.g. holidays + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. + * eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + disabledDates?: boolean | Array | any; + /**Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. + * eg disabledHours = [0, 1]; -> disabledHours will be { "0": true, "1": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + disabledHours?: boolean | Array | any; + /**Disables time selection between the given moments + * eg: [[moment({ h: 0 }), moment({ h: 8 })], [moment({ h: 18 }), moment({ h: 24 })]] + * @default: false + */ + disabledTimeIntervals?: boolean | Array>; + /**Disables selection of dates NOT in the array, e.g. holidays + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. + * eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + enabledDates?: boolean | Array | any; + /**Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. + * eg enabledHours = [0, 1]; -> enabledHours will be { "0": true, "1": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + enabledHours?: boolean | Array; + /**Allows for several input formats to be valid. See: https://github.com/Eonasdan/bootstrap-datetimepicker/pull/666 + * @default: false + */ + extraFormats?: boolean | Array; + /**If false, the textbox will not be given focus when the picker is shown + * @default: true + */ + focusOnShow?: boolean; + /**See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker. + * @default: false + */ + format?: boolean | string; + /**Change the default icons for the pickers functions. */ + icons?: Icons; + /**Allow date picker show event to fire even when the associated input element has the readonly="readonly"property. + * @default: false + */ + ignoreReadonly?: boolean; + /**Will display the picker inline without the need of a input field. This will also hide borders and shadows. + * @default: false + */ + inline?: boolean; + /**Allows for custom events to fire on keyboard press. + * eg: keybinds: { + * up: (widget) => console.log(widget), + * "control up": (widget) => console.log(widget) + * } + * The widget parameter is false, if the datepicker is closed. + */ + keyBinds?: { [key: string]: (widget: boolean | JQuery) => void }; + /**Will cause the date picker to not revert or overwrite invalid dates. + * @default: false + */ + keepInvalid?: boolean; + /**Will cause the date picker to stay open after selecting a date if no time components are being used. + * @default: false + */ + keepOpen?: boolean; + /**See momentjs for valid locales. You must include moment-with-locales.js or a local js file. + * @default: moment.locale() + */ + locale?: string; + /**Prevents date/time selections after this date. + * maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. + * @default: false + */ + maxDate?: boolean | moment.Moment | Date | string; + /**Prevents date/time selections before this date. + * minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. + * @default: false + */ + minDate?: boolean | moment.Moment | Date | string; + /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". + * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} + */ + parseInputDate?: (input: string) => moment.Moment; + /**Show the "Clear" button in the icon toolbar. + * Clicking the "Clear" button will set the calendar to null. + * @default: false + */ + showClear?: boolean; + /**Show the "Close" button in the icon toolbar. + * Clicking the "Close" button will call hide() + * @default: false + */ + showClose?: boolean; + /**Show the "Today" button in the icon toolbar. + * Clicking the "Today" button will set the calendar view and set the date to now. + * @default: false + */ + showTodayButton?: boolean; + /**Shows the picker side by side when using the time and date together. + * @default: false + */ + sideBySide?: boolean; + /**Number of minutes the up/down arrow's will move the minutes value in the time picker + * @default: 1 + */ + stepping?: number; + /**Changes the placement of the icon toolbar. + * @default: "default" + */ + toolbarPlacement?: "default" | "top" | "bottom"; + /**This will change the tooltips over each icon to a custom string */ + tooltips?: Tooltips; + /**On show, will set the picker to the current date/time + * @default: true + */ + useCurrent?: boolean; + /**Defines if moment should use strict date parsing when considering a date to be valid + * @default: false + */ + useStrict?: boolean; + /**This will change the viewDate without changing or setting the selected date. + * @default: false + */ + viewDate?: boolean | moment.Moment | Date | string; + /**The default view to display when the picker is shown. + * Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY + * @default: "days" + */ + viewMode?: "decades" | "years" | "months" | "days"; + /**On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative" + * @default: null + */ + widgetParent?: string | JQuery; + widgetPositioning?: WidgetPositioningOptions; } - interface DatetimepickerEventObject extends JQueryEventObject { + interface Icons { + /**default: "glyphicon glyphicon-trash" */ + clear?: string; + /**default: "glyphicon glyphicon-remove" */ + close?: string; + /**default: "glyphicon glyphicon-calendar" */ + date?: string; + /**default: "glyphicon glyphicon-time" */ + down?: string; + /**default: "glyphicon glyphicon-chevron-left" */ + next?: string; + /**default: "glyphicon glyphicon-screenshot" */ + previous?: string; + /**default: "glyphicon glyphicon-chevron-right" */ + time?: string; + /**default: "glyphicon glyphicon-chevron-down" */ + today?: string; + /**default: "glyphicon glyphicon-chevron-up" */ + up?: string; + } + + interface Tooltips { + today?: string; + clear?: string; + close?: string; + selectMonth?: string; + prevMonth?: string; + nextMonth?: string; + selectYear?: string; + prevYear?: string; + nextYear?: string; + selectDecade?: string; + prevDecade?: string; + nextDecade?: string; + prevCentury?: string; + nextCentury?: string; + selectTime?: string; + pickHour?: string; + incrementHour?: string; + decrementHour?: string; + pickMinute?: string; + incrementMinute?: string; + decrementMinute?: string; + togglePeriod?: string; + pickSecond?: string; + incrementSecond?: string; + decrementSecond?: string; + } + + interface WidgetPositioningOptions { + horizontal?: "auto" | "left" | "right"; + vertical?: "auto" | "top" | "bottom"; + } + + interface Event extends JQueryEventObject { date: moment.Moment; } - interface DatetimepickerIcons { - time?: string; - date?: string; - up?: string; - down?: string; - } - - interface DatetimepickerOptions { - pickDate?: boolean; - pickTime?: boolean; - useMinutes?: boolean; - useSeconds?: boolean; - useCurrent?: boolean; - minuteStepping?: number; - minDate?: moment.Moment | Date | string; - maxDate?: moment.Moment | Date | string; - showToday?: boolean; - collapse?: boolean; - language?: string; - defaultDate?: moment.Moment | Date | string; - disabledDates?: Array; - enabledDates?: Array; - icons?: DatetimepickerIcons; - useStrict?: boolean; - direction?: string; - sideBySide?: boolean; - daysOfWeekDisabled?: Array; - calendarWeeks?: boolean; - format?: string | boolean; - locale?: string; - showTodayButton?: boolean; - viewMode?: string; - inline?: boolean; - toolbarPlacement?: string; - showClear?: boolean; - ignoreReadonly?: boolean; - } - - interface Datetimepicker { - date(date: moment.Moment | Date | string): void; - date(): moment.Moment; - minDate(date: moment.Moment | Date | string): void; - minDate(): moment.Moment | boolean; - maxDate(date: moment.Moment | Date | string): void; - maxDate(): moment.Moment | boolean; - show(): void; - disable(): void; - enable(): void; - destroy(): void; - toggle(): void; + interface ChangeEvent extends Event { + /**Previous date. False if the previous date is null. */ + oldDate: moment.Moment | boolean; } + interface UpdateEvent extends JQueryEventObject { + /**Change type as a momentjs format token. e.g. yyyy on year change */ + change: string; + /**New viewDate. */ + viewDate: moment.Moment; + } } - interface JQuery { datetimepicker(): JQuery; datetimepicker(options: BootstrapV3DatetimePicker.DatetimepickerOptions): JQuery; - off(events: "dp.change", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; - off(events: "dp.change", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + data(key: "DateTimePicker"): BootstrapV3DatetimePicker.Datetimepicker; - on(events: "dp.change", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; - on(events: "dp.change", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; - on(events: 'dp.change', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; + on(events: "dp.change", handler: (eventObject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; + on(events: "dp.change", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; + on(events: "dp.change", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - off(events: "dp.show", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.show", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.change", handler: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; + off(events: "dp.change", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - on(events: "dp.show", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.show", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: 'dp.show', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.hide", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.hide", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.show", handler: (eventObject: BootstrapV3DatetimePicker.Event) => any): JQuery; + on(events: "dp.show", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + on(events: "dp.show", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.hide", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: 'dp.hide', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.show", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + off(events: "dp.show", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - off(events: "dp.error", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.error", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.error", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.error", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: 'dp.error', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.hide", handler: (eventObject: BootstrapV3DatetimePicker.Event) => any): JQuery; + on(events: "dp.hide", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - data(key: 'DateTimePicker'): BootstrapV3DatetimePicker.Datetimepicker; -} + off(events: "dp.hide", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + off(events: "dp.hide", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + + + on(events: "dp.error", handler: (eventObject: BootstrapV3DatetimePicker.Event) => any): JQuery; + on(events: "dp.error", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + on(events: "dp.error", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + + off(events: "dp.error", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + off(events: "dp.error", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + + + on(events: "dp.update", handler: (eventObject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; + on(events: "dp.update", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; + on(events: "dp.update", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; + + off(events: "dp.update", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; + off(events: "dp.update", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; +} \ No newline at end of file From ef767d98eeb9579b0154420f3625af666d4f8786 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Sat, 5 Mar 2016 17:12:54 +0100 Subject: [PATCH 12/72] Refactor the xrm.d.ts type definition file so that the Xrm object is accessible from any window obejct (window, parent, top, etc.) This requires to extract the exported functions and vars into a new interface (XrmStatic). --- xrm/xrm.d.ts | 729 ++++++++++++++++++++++++++++----------------------- 1 file changed, 395 insertions(+), 334 deletions(-) diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index a2f7c515b..1277b739c 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -1,9 +1,235 @@ -// Type definitions for Microsoft Dynamics xRM API v7.1 +// Compiled using typings@0.6.10 +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/1209610bb338b0e50d15920c82d8f4e312faee26/xrm/xrm.d.ts +// Type definitions for Microsoft Dynamics xRM API v7.1 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 -// Definitions by: David Berry , Matt Ngan +// Definitions by: David Berry , Matt Ngan , Markus Mauch // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Xrm +/** + * Injects the Xrm object and GetGlobalContext function into the global namespace. + */ +declare var Xrm: XrmStatic; +declare function GetGlobalContext(): XrmInterface.Context; + +/** + * Extends the Window interface defined in lib.d.ts and makes the Xrm object and GetGlobalContext function accessible from any window object (window, parent, top, etc.). + */ +interface Window +{ + /** + * A reference to the xRM global object. + */ + Xrm: XrmStatic; + + /** + * Gets the xRM application context, for HTML web resources, included by ClientGlobalContext.js.aspx + * @returns {Xrm.Context} The application context for the user's current session. + * @remarks The ClientGlobalContext.js.aspx page will include some global event handlers. These event handlers will + * cancel the onselectstart, contextmenu, and ondragstart events. + */ + GetGlobalContext(): XrmInterface.Context; +} + +/** + * Static xRM object. + */ +interface XrmStatic +{ + /** + * Provides a namespace container for the context, data and ui objects. + */ + Page: { + /** + * Provides methods to retrieve information specific to an organization, a user, or parameters passed to a page. + */ + context: XrmInterface.Context; + + /** + * Provides methods to work with the form. + */ + data: XrmInterface.Data; + + /** + * Contains properties and methods to retrieve information about the user interface as well as collections for several subcomponents of the form. + */ + ui: XrmInterface.Ui; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + getAttribute(): XrmInterface.Page.Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): XrmInterface.Page.Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + getAttribute( index: number ): XrmInterface.Page.Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + getAttribute( delegateFunction: XrmInterface.Collection.MatchingDelegate ): XrmInterface.Page.Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + getControl(): XrmInterface.Page.Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): XrmInterface.Page.Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + getControl( index: number ): XrmInterface.Page.Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + getControl( delegateFunction: XrmInterface.Collection.MatchingDelegate ): XrmInterface.Page.Control[]; + } + + /** + * Provides a container for useful functions not directly related to the current page. + */ + Utility: { + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + isActivityType( entityType: string ): boolean; + + /** + * Opens quick create. + * + * @param {Function} callback The function that will be called when a record is created. This + * function is passed a LookupValue object as a parameter. + * @param {string} entityLogicalName The logical name of the entity to create. + * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values + * based on mapped attribute values. + * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string + * parameters to the form. Invalid query string parameters will cause an + * error. + */ + openQuickCreate( + callback: ( recordReference: XrmInterface.Page.LookupValue ) => void, + entityLogicalName: string, + createFromEntity?: XrmInterface.Page.LookupValue, + parameters?: XrmInterface.Utility.OpenParameters ): void; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. + */ + openEntityForm( name: string, id?: string, parameters?: XrmInterface.Utility.FormOpenParameters, windowOptions?: XrmInterface.Utility.WindowOptions ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} + +/** + * Ghost module for the Xrm interfaces. + */ +declare module XrmInterface { /** * Interface for the client context. @@ -139,6 +365,170 @@ declare module Xrm prependOrgName( sPath: string ): string; } + /** + * Interface for the Xrm.Page.data object. + */ + export interface Data + { + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + refresh( save: boolean ): XrmInterface.Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + save(): XrmInterface.Async.XrmPromise; + + /** + * The record context of the form. + */ + entity: XrmInterface.Page.Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + process: XrmInterface.Page.data.ProcessManager; + } + + /** + * Interface for the Xrm.Page.ui object. + */ + export interface Ui + { + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + getFormType(): XrmInterface.Page.FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + setFormNotification( message: string, level: string, uniqueId: string ): boolean; + + process: XrmInterface.Page.data.ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + controls: XrmInterface.Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + formSelector: XrmInterface.Page.FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + navigation: XrmInterface.Page.Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + tabs: XrmInterface.Collection.ItemCollection; + } + /** * A definition module for asynchronous interface declarations. */ @@ -486,7 +876,7 @@ declare module Xrm * * @return The event source. */ - getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + getEventSource(): XrmInterface.Page.Attribute | XrmInterface.Page.Entity; /** * Gets the shared variable with the specified key. @@ -1302,34 +1692,6 @@ declare module Xrm * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. */ export type ProcessDictionary = { [index: string]: string }; - - /** - * Asynchronously refreshes data on the form, without reloading the page. - * - * @param {boolean} save true to save the record, after the refresh. - * - * @return An Async.XrmPromise. - */ - export function refresh( save: boolean ): Async.XrmPromise; - - /** - * Asynchronously saves the record. - * - * @return An Async.XrmPromise. - */ - export function save(): Async.XrmPromise; - - /** - * The record context of the form. - */ - export var entity: Entity; - - /** - * The process API for Xrm.Page.data. - * - * @remarks This member may be undefined when Process Flows are not used by the current entity. - */ - export var process: ProcessManager; } /** @@ -1767,7 +2129,7 @@ declare module Xrm * * @return The parent. */ - getParent(): typeof ui; + getParent(): XrmInterface.Ui; /** * Sets display state of the tab. @@ -1996,130 +2358,6 @@ declare module Xrm */ getEntityReference(): LookupValue; } - - /** - * Clears the form notification described by uniqueId. - * - * @param {string} uniqueId Unique identifier. - * - * @return true if it succeeds, otherwise false. - */ - export function clearFormNotification( uniqueId: string ): boolean; - - /** - * Closes the form. - */ - export function close(): void; - - /** - * Gets form type. - * - * @return The form type. - * - * @remarks Values returned are: 0 Undefined - * 1 Create - * 2 Update - * 3 Read Only - * 4 Disabled - * 6 Bulk Edit - * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) - */ - export function getFormType(): FormType; - - /** - * Gets view port height. - * - * @return The view port height, in pixels. - * - * @remarks This method does not work with Microsoft Dynamics CRM for tablets. - */ - export function getViewPortHeight(): number; - - /** - * Gets view port width. - * - * @return The view port width, in pixels. - * - * @remarks This method does not work with Microsoft Dynamics CRM for tablets. - */ - export function getViewPortWidth(): number; - - /** - * Re-evaluates the ribbon's configured EnableRules - * - * @remarks This method does not work with Microsoft Dynamics CRM for tablets. - */ - export function refreshRibbon(): void; - - /** - * Sets a form-level notification. - * - * @param {string} message The message. - * @param {"ERROR"} level An error message. - * @param {string} uniqueId A unique identifier for the message. - * - * @return true if it succeeds, false if it fails. - */ - export function setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; - - /** - * Sets a form-level notification. - * - * @param {string} message The message. - * @param {"WARNING"} level A warning message. - * @param {string} uniqueId A unique identifier for the message. - * - * @return true if it succeeds, false if it fails. - */ - export function setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; - - /** - * Sets a form-level notification. - * - * @param {string} message The message. - * @param {"INFO"} level An informational message. - * @param {string} uniqueId A unique identifier for the message. - * - * @return true if it succeeds, false if it fails. - */ - export function setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; - - /** - * Sets a form-level notification. - * - * @param {string} message The message. - * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". - * @param {string} uniqueId A unique identifier for the message. - * - * @return true if it succeeds, otherwise false. - */ - export function setFormNotification( message: string, level: string, uniqueId: string ): boolean; - - export var process: ProcessManager; - - /** - * A reference to the collection of controls on the form. - */ - export var controls: Collection.ItemCollection; - - /** - * The form selector API. - * - * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. - */ - export var formSelector: FormSelector; - - /** - * The navigation API. - * - * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. - */ - export var navigation: Navigation; - - /** - * A reference to the collection of tabs on the form. - */ - export var tabs: Collection.ItemCollection; } /** @@ -2193,99 +2431,6 @@ declare module Xrm */ items: Collection.ItemCollection; } - - /** - * A reference to the xRM application context. - */ - export var context: Context; - - /** - * Gets all attributes. - * - * @return An array of attributes. - */ - export function getAttribute(): Attribute[]; - - /** - * Gets an attribute matching attributeName. - * - * @tparam T An Attribute type. - * @param {string} attributeName Name of the attribute. - * - * @return The attribute. - */ - export function getAttribute( attributeName: string ): T; - - /** - * Gets an attribute matching attributeName. - * - * @param {string} attributeName Name of the attribute. - * - * @return The attribute. - */ - export function getAttribute( attributeName: string ): Attribute; - - /** - * Gets an attribute by index. - * - * @param {number} index The attribute index. - * - * @return The attribute. - */ - export function getAttribute( index: number ): Attribute; - - /** - * Gets an attribute. - * - * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function - * - * @return An array of attribute. - */ - export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; - - /** - * Gets all controls. - * - * @return An array of controls. - */ - export function getControl(): Control[]; - - /** - * Gets a control matching controlName. - * - * @tparam T A Control type - * @param {string} controlName Name of the control. - * - * @return The control. - */ - export function getControl( controlName: string ): T; - - /** - * Gets a control matching controlName. - * - * @param {string} controlName Name of the control. - * - * @return The control. - */ - export function getControl( controlName: string ): Control; - - /** - * Gets a control by index. - * - * @param {number} index The control index. - * - * @return The control. - */ - export function getControl( index: number ): Control; - - /** - * Gets a control. - * - * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. - * - * @return An array of control. - */ - export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; } /** @@ -2506,89 +2651,5 @@ declare module Xrm */ openInNewWindow: boolean; } - - /** - * Displays an alert dialog, with an "OK" button. - * - * @param {string} message The message. - * @param {function()} onCloseCallback The "OK" callback. - */ - export function alertDialog( message: string, onCloseCallback: () => void ): void; - - /** - * Displays a confirmation dialog, with "OK" and "Cancel" buttons. - * - * @param {string} message The message. - * @param {function()} yesCloseCallback The "OK" callback. - * @param {function()} noCloseCallback The "Cancel" callback. - */ - export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; - - /** - * Query if 'entityType' is an Activity entity. - * - * @param {string} entityType Type of the entity. - * - * @return true if the entity is an Activity, false if not. - */ - export function isActivityType( entityType: string ): boolean; - - /** - * Opens an entity form. - * - * @param {string} name The entity's logical name. - * @param {string} id (Optional) The unique identifier for the record. - * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. - * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. - */ - export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters, windowOptions?: WindowOptions ): void; - - /** - * Opens quick create. - * - * @param {Function} callback The function that will be called when a record is created. This - * function is passed a LookupValue object as a parameter. - * @param {string} entityLogicalName The logical name of the entity to create. - * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values - * based on mapped attribute values. - * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string - * parameters to the form. Invalid query string parameters will cause an - * error. - */ - export function openQuickCreate( callback: ( recordReference: Page.LookupValue ) => void, - entityLogicalName: string, - createFromEntity?: Page.LookupValue, - parameters?: OpenParameters ): void; - - /** - * Opens an HTML Web Resource in a new browser window. - * - * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL - * parameters. See Remarks. - * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. - * It is advised to use encodeURIcomponent() to encode the value. - * @param {number} width (Optional) The width of the new window. - * @param {number} height (Optional) The height of the new window. - * - * @return A Window reference, containing the opened Web Resource. - * - * @remarks This function will not work with Microsoft Dynamics CRM for tablets. - * Valid WebResource URL Parameters: typename - * type - * id - * orgname - * userlcid - * data (identical to this method's webResourceData parameter) - * formid - */ - export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; } } - -/** - * Gets the xRM application context, for HTML web resources, included by ClientGlobalContext.js.aspx - * @returns {Xrm.Context} The application context for the user's current session. - * @remarks The ClientGlobalContext.js.aspx page will include some global event handlers. These event handlers will - * cancel the onselectstart, contextmenu, and ondragstart events. - */ -declare function GetGlobalContext(): Xrm.Context; From 6ec585e2d6007cc3427576c50e71baf2d5ee7702 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Sat, 5 Mar 2016 17:23:35 +0100 Subject: [PATCH 13/72] Make tests work again --- xrm/parature.d.ts | 2 +- xrm/xrm-tests.ts | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/xrm/parature.d.ts b/xrm/parature.d.ts index 030c97b68..fd388ea80 100644 --- a/xrm/parature.d.ts +++ b/xrm/parature.d.ts @@ -12,7 +12,7 @@ declare module Xrm.Page * * @sa Control */ - export interface KbSearchControl extends Control + export interface KbSearchControl extends XrmInterface.Page.Control { /** * Use this method to add an event handler to the OnResultOpened event. diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts index 50fd36955..fe39fe2f4 100644 --- a/xrm/xrm-tests.ts +++ b/xrm/xrm-tests.ts @@ -27,11 +27,11 @@ var grids = Xrm.Page.getControl(( control ) => return control.getControlType() === "subgrid"; }); -var selectedGridReferences: Xrm.Page.LookupValue[] = []; +var selectedGridReferences: XrmInterface.Page.LookupValue[] = []; /// Demonstrate iterator typing with v7.1 additions -grids.forEach(( gridControl: Xrm.Page.GridControl ) => +grids.forEach(( gridControl: XrmInterface.Page.GridControl ) => { gridControl.getGrid().getSelectedRows().forEach(( row ) => { @@ -41,8 +41,8 @@ grids.forEach(( gridControl: Xrm.Page.GridControl ) => /// Demonstrate generic overload vs typecast -var lookupAttribute = Xrm.Page.getControl( "customerid" ); -var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); +var lookupAttribute = Xrm.Page.getControl( "customerid" ); +var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); /// Demonstrate ES6 String literal syntax @@ -91,7 +91,7 @@ Xrm.Page.data.entity.addOnSave(( context ) => { var eventArgs = context.getEventArgs(); - if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + if ( eventArgs.getSaveMode() === XrmInterface.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === XrmInterface.Page.SaveMode.SaveAndClose ) eventArgs.preventDefault(); }); From a40550cf0882290277a096a212ba5be8a76097a8 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Sat, 5 Mar 2016 17:34:42 +0100 Subject: [PATCH 14/72] Make header compliant with the test script --- xrm/xrm.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index 1277b739c..ff1828661 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -1,5 +1,3 @@ -// Compiled using typings@0.6.10 -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/1209610bb338b0e50d15920c82d8f4e312faee26/xrm/xrm.d.ts // Type definitions for Microsoft Dynamics xRM API v7.1 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 // Definitions by: David Berry , Matt Ngan , Markus Mauch From d60e6cb19bce15d2e5a54e60edc3b9a6cbe00e97 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Tue, 8 Mar 2016 13:28:10 +0100 Subject: [PATCH 15/72] Merged XrmInterface with XrmStatic into one global Xrm namespace Factored out all enums into XrmEnum so that the Xrm module becomes a non-instantiated module. --- xrm/parature.d.ts | 2 +- xrm/xrm-tests.ts | 15 +- xrm/xrm.d.ts | 564 ++++++++++++++++++++++------------------------ 3 files changed, 285 insertions(+), 296 deletions(-) diff --git a/xrm/parature.d.ts b/xrm/parature.d.ts index fd388ea80..009f27b4b 100644 --- a/xrm/parature.d.ts +++ b/xrm/parature.d.ts @@ -12,7 +12,7 @@ declare module Xrm.Page * * @sa Control */ - export interface KbSearchControl extends XrmInterface.Page.Control + export interface KbSearchControl extends Xrm.Page.Control { /** * Use this method to add an event handler to the OnResultOpened event. diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts index fe39fe2f4..4dfb8e409 100644 --- a/xrm/xrm-tests.ts +++ b/xrm/xrm-tests.ts @@ -1,6 +1,11 @@ /// /// +/// Demonstrate usage in the browser's window object + +window.Xrm.Utility.alertDialog( "message", () => {} ); +parent.Xrm.Page.context.getOrgLcid(); + /// Demonstrate clientglobalcontext.d.ts function _getContext() @@ -27,11 +32,11 @@ var grids = Xrm.Page.getControl(( control ) => return control.getControlType() === "subgrid"; }); -var selectedGridReferences: XrmInterface.Page.LookupValue[] = []; +var selectedGridReferences: Xrm.Page.LookupValue[] = []; /// Demonstrate iterator typing with v7.1 additions -grids.forEach(( gridControl: XrmInterface.Page.GridControl ) => +grids.forEach(( gridControl: Xrm.Page.GridControl ) => { gridControl.getGrid().getSelectedRows().forEach(( row ) => { @@ -41,8 +46,8 @@ grids.forEach(( gridControl: XrmInterface.Page.GridControl ) => /// Demonstrate generic overload vs typecast -var lookupAttribute = Xrm.Page.getControl( "customerid" ); -var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); +var lookupAttribute = Xrm.Page.getControl( "customerid" ); +var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); /// Demonstrate ES6 String literal syntax @@ -91,7 +96,7 @@ Xrm.Page.data.entity.addOnSave(( context ) => { var eventArgs = context.getEventArgs(); - if ( eventArgs.getSaveMode() === XrmInterface.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === XrmInterface.Page.SaveMode.SaveAndClose ) + if ( eventArgs.getSaveMode() === XrmEnum.SaveMode.AutoSave || eventArgs.getSaveMode() === XrmEnum.SaveMode.SaveAndClose ) eventArgs.preventDefault(); }); diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index ff1828661..716b09799 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -3,232 +3,213 @@ // Definitions by: David Berry , Matt Ngan , Markus Mauch // Definitions: https://github.com/borisyankov/DefinitelyTyped -/** - * Injects the Xrm object and GetGlobalContext function into the global namespace. - */ -declare var Xrm: XrmStatic; -declare function GetGlobalContext(): XrmInterface.Context; +declare var Xrm: Xrm.XrmStatic; +declare function GetGlobalContext(): Xrm.Context; -/** - * Extends the Window interface defined in lib.d.ts and makes the Xrm object and GetGlobalContext function accessible from any window object (window, parent, top, etc.). - */ interface Window { - /** - * A reference to the xRM global object. - */ - Xrm: XrmStatic; - - /** - * Gets the xRM application context, for HTML web resources, included by ClientGlobalContext.js.aspx - * @returns {Xrm.Context} The application context for the user's current session. - * @remarks The ClientGlobalContext.js.aspx page will include some global event handlers. These event handlers will - * cancel the onselectstart, contextmenu, and ondragstart events. - */ - GetGlobalContext(): XrmInterface.Context; + Xrm: Xrm.XrmStatic; + GetGlobalContext(): Xrm.Context; } -/** - * Static xRM object. - */ -interface XrmStatic +declare module Xrm { /** - * Provides a namespace container for the context, data and ui objects. + * Static xRM object. */ - Page: { + export interface XrmStatic + { /** - * Provides methods to retrieve information specific to an organization, a user, or parameters passed to a page. + * Provides a namespace container for the context, data and ui objects. */ - context: XrmInterface.Context; - - /** - * Provides methods to work with the form. - */ - data: XrmInterface.Data; - - /** - * Contains properties and methods to retrieve information about the user interface as well as collections for several subcomponents of the form. - */ - ui: XrmInterface.Ui; - - /** - * Gets all attributes. - * - * @return An array of attributes. - */ - getAttribute(): XrmInterface.Page.Attribute[]; + Page: { + /** + * Provides methods to retrieve information specific to an organization, a user, or parameters passed to a page. + */ + context: Context; + + /** + * Provides methods to work with the form. + */ + data: Data; + + /** + * Contains properties and methods to retrieve information about the user interface as well as collections for several subcomponents of the form. + */ + ui: Ui; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + getAttribute(): Page.Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): Page.Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + getAttribute( index: number ): Page.Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + getAttribute( delegateFunction: Collection.MatchingDelegate ): Page.Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + getControl(): Page.Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): Page.Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + getControl( index: number ): Page.Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + getControl( delegateFunction: Collection.MatchingDelegate ): Page.Control[]; + } /** - * Gets an attribute matching attributeName. - * - * @tparam T An Attribute type. - * @param {string} attributeName Name of the attribute. - * - * @return The attribute. + * Provides a container for useful functions not directly related to the current page. */ - getAttribute( attributeName: string ): T; + Utility: { + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + alertDialog( message: string, onCloseCallback: () => void ): void; - /** - * Gets an attribute matching attributeName. - * - * @param {string} attributeName Name of the attribute. - * - * @return The attribute. - */ - getAttribute( attributeName: string ): XrmInterface.Page.Attribute; + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; - /** - * Gets an attribute by index. - * - * @param {number} index The attribute index. - * - * @return The attribute. - */ - getAttribute( index: number ): XrmInterface.Page.Attribute; + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + isActivityType( entityType: string ): boolean; - /** - * Gets an attribute. - * - * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function - * - * @return An array of attribute. - */ - getAttribute( delegateFunction: XrmInterface.Collection.MatchingDelegate ): XrmInterface.Page.Attribute[]; + /** + * Opens quick create. + * + * @param {Function} callback The function that will be called when a record is created. This + * function is passed a LookupValue object as a parameter. + * @param {string} entityLogicalName The logical name of the entity to create. + * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values + * based on mapped attribute values. + * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string + * parameters to the form. Invalid query string parameters will cause an + * error. + */ + openQuickCreate( + callback: ( recordReference: Page.LookupValue ) => void, + entityLogicalName: string, + createFromEntity?: Page.LookupValue, + parameters?: Utility.OpenParameters ): void; - /** - * Gets all controls. - * - * @return An array of controls. - */ - getControl(): XrmInterface.Page.Control[]; + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. + */ + openEntityForm( name: string, id?: string, parameters?: Utility.FormOpenParameters, windowOptions?: Utility.WindowOptions ): void; - /** - * Gets a control matching controlName. - * - * @tparam T A Control type - * @param {string} controlName Name of the control. - * - * @return The control. - */ - getControl( controlName: string ): T; - - /** - * Gets a control matching controlName. - * - * @param {string} controlName Name of the control. - * - * @return The control. - */ - getControl( controlName: string ): XrmInterface.Page.Control; - - /** - * Gets a control by index. - * - * @param {number} index The control index. - * - * @return The control. - */ - getControl( index: number ): XrmInterface.Page.Control; - - /** - * Gets a control. - * - * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. - * - * @return An array of control. - */ - getControl( delegateFunction: XrmInterface.Collection.MatchingDelegate ): XrmInterface.Page.Control[]; + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } } - - /** - * Provides a container for useful functions not directly related to the current page. - */ - Utility: { - /** - * Displays an alert dialog, with an "OK" button. - * - * @param {string} message The message. - * @param {function()} onCloseCallback The "OK" callback. - */ - alertDialog( message: string, onCloseCallback: () => void ): void; - - /** - * Displays a confirmation dialog, with "OK" and "Cancel" buttons. - * - * @param {string} message The message. - * @param {function()} yesCloseCallback The "OK" callback. - * @param {function()} noCloseCallback The "Cancel" callback. - */ - confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; - - /** - * Query if 'entityType' is an Activity entity. - * - * @param {string} entityType Type of the entity. - * - * @return true if the entity is an Activity, false if not. - */ - isActivityType( entityType: string ): boolean; - - /** - * Opens quick create. - * - * @param {Function} callback The function that will be called when a record is created. This - * function is passed a LookupValue object as a parameter. - * @param {string} entityLogicalName The logical name of the entity to create. - * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values - * based on mapped attribute values. - * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string - * parameters to the form. Invalid query string parameters will cause an - * error. - */ - openQuickCreate( - callback: ( recordReference: XrmInterface.Page.LookupValue ) => void, - entityLogicalName: string, - createFromEntity?: XrmInterface.Page.LookupValue, - parameters?: XrmInterface.Utility.OpenParameters ): void; - - /** - * Opens an entity form. - * - * @param {string} name The entity's logical name. - * @param {string} id (Optional) The unique identifier for the record. - * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. - * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. - */ - openEntityForm( name: string, id?: string, parameters?: XrmInterface.Utility.FormOpenParameters, windowOptions?: XrmInterface.Utility.WindowOptions ): void; - /** - * Opens an HTML Web Resource in a new browser window. - * - * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL - * parameters. See Remarks. - * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. - * It is advised to use encodeURIcomponent() to encode the value. - * @param {number} width (Optional) The width of the new window. - * @param {number} height (Optional) The height of the new window. - * - * @return A Window reference, containing the opened Web Resource. - * - * @remarks This function will not work with Microsoft Dynamics CRM for tablets. - * Valid WebResource URL Parameters: typename - * type - * id - * orgname - * userlcid - * data (identical to this method's webResourceData parameter) - * formid - */ - openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; - } -} - -/** - * Ghost module for the Xrm interfaces. - */ -declare module XrmInterface -{ /** * Interface for the client context. */ @@ -252,7 +233,7 @@ declare module XrmInterface /** * Interface for the xRM application context. */ - export interface Context + interface Context { /** * The client's context instance. @@ -375,26 +356,26 @@ declare module XrmInterface * * @return An Async.XrmPromise. */ - refresh( save: boolean ): XrmInterface.Async.XrmPromise; + refresh( save: boolean ): Async.XrmPromise; /** * Asynchronously saves the record. * * @return An Async.XrmPromise. */ - save(): XrmInterface.Async.XrmPromise; - + save(): Async.XrmPromise; + /** * The record context of the form. */ - entity: XrmInterface.Page.Entity; + entity: Page.Entity; /** * The process API for Xrm.Page.data. * * @remarks This member may be undefined when Process Flows are not used by the current entity. */ - process: XrmInterface.Page.data.ProcessManager; + process: Page.data.ProcessManager; } /** @@ -429,7 +410,7 @@ declare module XrmInterface * 6 Bulk Edit * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) */ - getFormType(): XrmInterface.Page.FormType; + getFormType(): XrmEnum.FormType; /** * Gets view port height. @@ -500,31 +481,31 @@ declare module XrmInterface */ setFormNotification( message: string, level: string, uniqueId: string ): boolean; - process: XrmInterface.Page.data.ProcessManager; + process: Page.data.ProcessManager; /** * A reference to the collection of controls on the form. */ - controls: XrmInterface.Collection.ItemCollection; + controls: Collection.ItemCollection; /** * The form selector API. * * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. */ - formSelector: XrmInterface.Page.FormSelector; + formSelector: Page.FormSelector; /** * The navigation API. * * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. */ - navigation: XrmInterface.Page.Navigation; + navigation: Page.Navigation; /** * A reference to the collection of tabs on the form. */ - tabs: XrmInterface.Collection.ItemCollection; + tabs: Collection.ItemCollection; } /** @@ -665,63 +646,6 @@ declare module XrmInterface */ export module Page { - /** - * Enumeration of entity form states/types. - */ - export const enum FormType - { - Undefined = 0, - Create = 1, - Update = 2, - ReadOnly = 3, - Disabled = 4, - BulkEdit = 6 - } - - /** - * Enumeration of entity form save modes. - */ - export const enum SaveMode - { - Save = 1, - SaveAndClose = 2, - SaveAndNew = 59, - AutoSave = 70, - SaveAsCompleted = 58, - Deactivate = 5, - Reactivate = 6, - Assign = 47, - Send = 7, - Qualify = 16, - Disqualify = 15 - } - - /** - * Enumeration of stage categories. - */ - export const enum StageCategory - { - Qualify = 0, - Develop = 1, - Propose = 2, - Close = 3, - Identify = 4, - Research = 5, - Resolve = 6 - } - - /** - * Enumeration of grid control context resolutions. - */ - export const enum GridControlContext - { - Unknown = 0, - RibbonContextForm = 1, - RibbonContextListing = 2, - FormContextUnrelated = 3, - FormContextRelated = 4 - } - /** * Interface for a CRM Business Process Flow instance. */ @@ -769,7 +693,7 @@ declare module XrmInterface * * @return The stage category. */ - getCategory(): { getValue(): StageCategory }; + getCategory(): { getValue(): XrmEnum.StageCategory }; /** * Returns the logical name of the entity associated with the stage. @@ -874,7 +798,7 @@ declare module XrmInterface * * @return The event source. */ - getEventSource(): XrmInterface.Page.Attribute | XrmInterface.Page.Entity; + getEventSource(): Page.Attribute | Page.Entity; /** * Gets the shared variable with the specified key. @@ -1552,7 +1476,7 @@ declare module XrmInterface * 16 Qualify (Lead) * 15 Disqualify (Lead) */ - getSaveMode(): SaveMode; + getSaveMode(): XrmEnum.SaveMode; /** * Returns a boolean value to indicate if the record's save has been prevented. @@ -1972,7 +1896,7 @@ declare module XrmInterface * * @return The context type. */ - getContextType(): GridControlContext; + getContextType(): XrmEnum.GridControlContext; /** * Use this method to get the logical name of the entity data displayed in the grid. @@ -2127,7 +2051,7 @@ declare module XrmInterface * * @return The parent. */ - getParent(): XrmInterface.Ui; + getParent(): Ui; /** * Sets display state of the tab. @@ -2438,15 +2362,6 @@ declare module XrmInterface */ export module Url { - /** - * An enumeration for view types. - */ - export const enum ViewType - { - SystemView = 1039, - UserView = 4230 - } - /** * Interface for defining parameters on a request to open a form with main.aspx (as with * window.open). Useful for parsing the keys and values into a string of the format: @@ -2519,7 +2434,7 @@ declare module XrmInterface * @remarks Accepted values are: 1039 System View * 4230 User View. */ - viewtype: ViewType; + viewtype: XrmEnum.ViewType; /** * Controls whether the command bar is displayed. @@ -2651,3 +2566,72 @@ declare module XrmInterface } } } + +declare module XrmEnum +{ + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + /** + * Enumeration of grid control context resolutions. + */ + export const enum GridControlContext + { + Unknown = 0, + RibbonContextForm = 1, + RibbonContextListing = 2, + FormContextUnrelated = 3, + FormContextRelated = 4 + } + + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } +} \ No newline at end of file From 735772cee9f8d6bae39b61dd7715ab0f8314397c Mon Sep 17 00:00:00 2001 From: Tom Shen Date: Tue, 8 Mar 2016 14:19:25 -0500 Subject: [PATCH 16/72] Add useRouterHistory to react-router type definitions --- react-router/react-router.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index e87622e9b..e510b7406 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -395,6 +395,14 @@ declare module "react-router/lib/match" { } +declare module "react-router/lib/useRouterHistory" { + interface CreateRouterHistory { + (options?: HistoryModule.HistoryOptions): HistoryModule.History & HistoryModule.HistoryQueries; + } + + export default function useRouterHistory(createHistory: HistoryModule.CreateHistory): CreateRouterHistory; +} + declare module "react-router" { @@ -434,6 +442,8 @@ declare module "react-router" { import match from "react-router/lib/match" + import useRouterHistory from "react-router/lib/useRouterHistory"; + // PlainRoute is defined in the API documented at: // https://github.com/rackt/react-router/blob/master/docs/API.md // but not included in any of the .../lib modules above. @@ -472,7 +482,8 @@ declare module "react-router" { formatPattern, RouterContext, PropTypes, - match + match, + useRouterHistory } export default Router From ce4e392818056d51419483b8546c3a2330f4ecc9 Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Fri, 11 Mar 2016 09:38:21 +0000 Subject: [PATCH 17/72] Update inversify.d.ts --- inversify/inversify.d.ts | 176 +++++++++++++++++++++++++++++---------- 1 file changed, 134 insertions(+), 42 deletions(-) diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index f3c924e82..12a8c0111 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,51 +1,143 @@ -// Type definitions for inversify 1.0.0 +// Type definitions for inversify 2.0.0-alpha.3 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module inversify { - - interface TypeBindingInterface { - runtimeIdentifier : string; - implementationType : { new(): TServiceType ;}; - cache : TServiceType; - scope : number; // TypeBindingScopeEnum - } +/// - interface KernelInterface { - bind(typeBinding : TypeBindingInterface) : void; - unbind(runtimeIdentifier : string) : void; - unbindAll() : void; - resolve(runtimeIdentifier : string) : TImplementationType; - } +declare namespace inversify { - enum TypeBindingScopeEnum { - Transient = 0, - Singleton = 1, - } + interface IKernelConstructor { + new(options?: IKernelOptions): IKernel; + } - class TypeBinding implements TypeBindingInterface { - runtimeIdentifier: string; - implementationType: { - new (): TServiceType; - }; - cache: TServiceType; - scope: TypeBindingScopeEnum; - constructor(runtimeIdentifier: string, implementationType: { - new (...args: any[]): TServiceType; - }, scopeType?: TypeBindingScopeEnum); - } + export interface IKernel { + bind(runtimeIdentifier: string): IBindingToSyntax; + unbind(runtimeIdentifier: string): void; + unbindAll(): void; + get(runtimeIdentifier: string): T; + getAll(runtimeIdentifier: string): T[]; + } - class Kernel implements KernelInterface { - private _bindings; - bind(typeBinding: TypeBindingInterface): void; - unbind(runtimeIdentifier: string): void; - unbindAll(): void; - resolve(runtimeIdentifier: string): TImplementationType; - private _validateBinding(typeBinding); - private _getConstructorArguments(func); - private _injectDependencies(func); - private _construct(constr, args); - constructor(); - } + export interface IKernelOptions { + middleware?: IMiddleware[]; + modules?: IKernelModule[]; + } + + interface IMiddleware extends Function { + (...args: any[]): any; + } + + export interface IKernelModule extends Function { + (kernel: IKernel): void; + } + + interface IBindingToSyntax { + to(constructor: { new(...args: any[]): T; }): IBindingInWhenProxySyntax; + toValue(value: T): IBindingInWhenProxySyntax; + toConstructor(constructor: INewable): IBindingInWhenProxySyntax; + toFactory(factory: IFactoryCreator): IBindingInWhenProxySyntax; + toAutoFactory(): IBindingInWhenProxySyntax; + toProvider(provider: IProviderCreator): IBindingInWhenProxySyntax; + } + + interface IBindingInWhenProxySyntax { + inTransientScope(): IBindingInWhenProxySyntax; + inSingletonScope(): IBindingInWhenProxySyntax; + when(constraint: (request: IRequest) => boolean): IBindingInWhenProxySyntax; + whenTargetNamed(name: string): IBindingInWhenProxySyntax; + whenTargetTagged(tag: string, value: any): IBindingInWhenProxySyntax; + proxy(fn: (injectable: T) => T): IBindingInWhenProxySyntax; + } + + export interface IFactory extends Function { + (): T; + } + + interface IFactoryCreator extends Function { + (context: IContext): IFactory; + } + + export interface INewable { + new(...args: any[]): T; + } + + export interface IProvider extends Function { + (): Promise; + } + + interface IProviderCreator extends Function { + (context: IContext): IProvider; + } + + export interface IContext { + kernel: IKernel; + plan: IPlan; + addPlan(plan: IPlan); + } + + export interface IPlan { + parentContext: IContext; + rootRequest: IRequest; + } + + export interface IRequest { + service: string; + parentContext: IContext; + parentRequest: IRequest; + childRequests: IRequest[]; + target: ITarget; + bindings: IBinding[]; + addChildRequest( + service: string, + bindings: (IBinding|IBinding[]), + target: ITarget): IRequest; + } + + export interface IBinding { + runtimeIdentifier: string; + implementationType: INewable; + factory: IFactoryCreator; + provider: IProviderCreator; + constraint: (request: IRequest) => boolean; + proxyMaker: (injectable: T) => T; + cache: T; + scope: number; // BindingScope + type: number; // BindingType + } + + export interface ITarget { + service: IQueryableString; + name: IQueryableString; + metadata: Array; + isArray(): boolean; + isNamed(): boolean; + isTagged(): boolean; + matchesName(name: string): boolean; + matchesTag(name: IMetadata): boolean; + } + + export interface IQueryableString { + startsWith(searchString: string): boolean; + endsWith(searchString: string): boolean; + contains(searchString: string): boolean; + equals(compareString: string): boolean; + value(): string; + } + + export interface IMetadata { + key: string; + value: any; + } + + export var Kernel: IKernelConstructor; + export var decorate: any; + export function inject(...typeIdentifiers: string[]): (typeConstructor: any) => void; + export var tagged: any; + export var named: any; + export var paramNames: any; +} + +declare module "inversify" { + export = inversify; } From 133429541909106abf1b391e5fcd9555b12c1ff1 Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Fri, 11 Mar 2016 09:39:12 +0000 Subject: [PATCH 18/72] Update inversify-tests.ts --- inversify/inversify-tests.ts | 269 +++++++++++++++++++++++++---------- 1 file changed, 197 insertions(+), 72 deletions(-) diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 46b5cab97..c69bd064e 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -1,75 +1,200 @@ /// -interface FooInterface { - name : string; - greet() : string; +import { + Kernel, + inject, tagged, named, paramNames, + IKernel, IKernelOptions, INewable, + IKernelModule, IFactory, IProvider, IRequest +} from "inversify"; + +module external_module_test { + + interface INinja { + fight(): string; + sneak(): string; + } + + interface IKatana { + hit(): string; + } + + interface IShuriken { + throw(); + } + + class Katana implements IKatana { + public hit() { + return "cut!"; + } + } + + class Shuriken implements IShuriken { + public throw() { + return "hit!"; + } + } + + @inject("IKatana", "IShuriken") + class Ninja implements INinja { + + private _katana: IKatana; + private _shuriken: IShuriken; + + public constructor(katana: IKatana, shuriken: IShuriken) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel = new Kernel(); + kernel.bind("INinja").to(Ninja); + kernel.bind("IKatana").to(Katana); + kernel.bind("IShuriken").to(Shuriken).inSingletonScope(); + + let ninja = kernel.get("INinja"); + console.log(ninja); + + // Unbind + kernel.unbind("INinja"); + kernel.unbindAll(); + + // Kernel modules + let module: IKernelModule = (k: IKernel) => { + k.bind("INinja").to(Ninja); + k.bind("IKatana").to(Katana).inTransientScope(); + k.bind("IShuriken").to(Shuriken).inSingletonScope(); + }; + + let options: IKernelOptions = { + middleware: [], + modules: [module] + }; + + kernel = new Kernel(options); + let ninja2 = kernel.get("INinja"); + console.log(ninja2); + + // binding types + kernel.bind("IKatana").to(Katana); + kernel.bind("IKatana").toValue(new Katana()); + + kernel.bind>("IKatana").toConstructor(Katana); + + kernel.bind>("IKatana").toFactory((context) => { + return () => { + return kernel.get("IKatana"); + }; + }); + + kernel.bind>("IKatana").toAutoFactory(); + + kernel.bind>("IKatana").toProvider((context) => { + return () => { + return new Promise((resolve) => { + let katana = kernel.get("IKatana"); + resolve(katana); + }); + }; + }); + + kernel.bind("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => { + // BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha + /* + let handler = { + apply: function(target, thisArgument, argumentsList) { + console.log(`Starting: ${performance.now()}`); + let result = target.apply(thisArgument, argumentsList); + console.log(`Finished: ${performance.now()}`); + return result; + } + }; + return new Proxy(katanaToBeInjected, handler); + */ + return katanaToBeInjected; + }); + + interface IWeapon {} + interface ISamurai { + katana: IWeapon; + shuriken: IWeapon; + } + + @inject("IWeapon", "IWeapon") + class Samurai implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + @tagged("canThrow", false) katana: IWeapon, + @tagged("canThrow", true) shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + kernel.bind("Samurai").to(Samurai); + kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + + let throwable = tagged("canThrow", true); + let notThrowable = tagged("canThrow", false); + + @inject("IWeapon", "IWeapon") + class Samurai2 implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + @throwable("canThrow", false) katana: IWeapon, + @notThrowable("canThrow", true) shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + @inject("IWeapon", "IWeapon") + class Samurai3 implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + @named("strong") katana: IWeapon, + @named("weak") shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + kernel.bind("ISamurai").to(Samurai3); + kernel.bind("IWeapon").to(Katana).whenTargetNamed("strong"); + kernel.bind("IWeapon").to(Shuriken).whenTargetNamed("weak"); + + @inject("IWeapon", "IWeapon") + @paramNames("katana", "shuriken") + class Samurai4 implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + katana: IWeapon, + shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + kernel.bind("ISamurai").to(Samurai4); + + kernel.bind("IWeapon").to(Katana).when((request: IRequest) => { + return request.target.name.equals("katana"); + }); + + kernel.bind("IWeapon").to(Shuriken).when((request: IRequest) => { + return request.target.name.equals("shuriken"); + }); + } - -interface BarInterface { - name : string; - greet() : string; -} - -interface FooBarInterface { - foo : FooInterface; - bar : BarInterface; - greet() : string; -} - -class Foo implements FooInterface { - public name : string; - constructor() { - this.name = "foo"; - } - public greet() : string { - return this.name; - } -} - -class Bar implements BarInterface { - public name : string; - constructor() { - this.name = "bar"; - } - public greet() : string { - return this.name; - } -} - -class FooBar implements FooBarInterface { - public foo : FooInterface; - public bar : BarInterface; - constructor(FooInterface : FooInterface, BarInterface : BarInterface) { - this.foo = FooInterface; - this.bar = BarInterface; - } - public greet() : string{ - return this.foo.greet() + this.bar.greet(); - } -} - -// Kernel -var kernel = new inversify.Kernel(); - -// Identifiers -var fooRuntimeIdentifier = "FooInterface"; -var barRuntimeIdentifier = "BarInterface"; -var fooBarRuntimeIdentifier = "FooBarInterface"; - -// Bindings -var fooBinding = new inversify.TypeBinding(fooRuntimeIdentifier, Foo); -var barBinding = new inversify.TypeBinding(barRuntimeIdentifier, Bar); -var fooBarBinding = new inversify.TypeBinding(fooBarRuntimeIdentifier, FooBar); - -kernel.bind(fooBinding); -kernel.bind(barBinding); -kernel.bind(fooBarBinding); - -// Resolve -var foo = kernel.resolve(fooRuntimeIdentifier); -var bar = kernel.resolve(barRuntimeIdentifier); -var fooBar = kernel.resolve(fooBarRuntimeIdentifier); - -// Unbind -kernel.unbind(fooRuntimeIdentifier); -kernel.unbindAll(); From 6a1654c23b5ced95935974f994b27099e8d0ee3f Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Fri, 11 Mar 2016 09:40:41 +0000 Subject: [PATCH 19/72] Create inversify-global-tests.ts --- inversify/inversify-global-tests.ts | 193 ++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 inversify/inversify-global-tests.ts diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts new file mode 100644 index 000000000..902f23aea --- /dev/null +++ b/inversify/inversify-global-tests.ts @@ -0,0 +1,193 @@ +/// + +module global_module_test { + + interface INinja { + fight(): string; + sneak(): string; + } + + interface IKatana { + hit(): string; + } + + interface IShuriken { + throw(); + } + + class Katana implements IKatana { + public hit() { + return "cut!"; + } + } + + class Shuriken implements IShuriken { + public throw() { + return "hit!"; + } + } + + @inversify.inject("IKatana", "IShuriken") + class Ninja implements INinja { + + private _katana: IKatana; + private _shuriken: IShuriken; + + public constructor(katana: IKatana, shuriken: IShuriken) { + this._katana = katana; + this._shuriken = shuriken; + } + + public fight() { return this._katana.hit(); }; + public sneak() { return this._shuriken.throw(); }; + + } + + let kernel = new inversify.Kernel(); + kernel.bind("INinja").to(Ninja); + kernel.bind("IKatana").to(Katana); + kernel.bind("IShuriken").to(Shuriken).inSingletonScope(); + + let ninja = kernel.get("INinja"); + console.log(ninja); + + // Unbind + kernel.unbind("INinja"); + kernel.unbindAll(); + + // Kernel modules + let module: inversify.IKernelModule = (k: inversify.IKernel) => { + k.bind("INinja").to(Ninja); + k.bind("IKatana").to(Katana).inTransientScope(); + k.bind("IShuriken").to(Shuriken).inSingletonScope(); + }; + + let options: inversify.IKernelOptions = { + middleware: [], + modules: [module] + }; + + kernel = new inversify.Kernel(options); + let ninja2 = kernel.get("INinja"); + console.log(ninja2); + + // binding types + kernel.bind("IKatana").to(Katana); + kernel.bind("IKatana").toValue(new Katana()); + + kernel.bind>("IKatana").toConstructor(Katana); + + kernel.bind>("IKatana").toFactory((context) => { + return () => { + return kernel.get("IKatana"); + }; + }); + + kernel.bind>("IKatana").toAutoFactory(); + + kernel.bind>("IKatana").toProvider((context) => { + return () => { + return new Promise((resolve) => { + let katana = kernel.get("IKatana"); + resolve(katana); + }); + }; + }); + + kernel.bind("IKatana").to(Katana).proxy((katanaToBeInjected: IKatana) => { + // BLOCK http://stackoverflow.com/questions/35906938/how-to-enable-harmony-proxies-in-gulp-mocha + /* + let handler = { + apply: function(target, thisArgument, argumentsList) { + console.log(`Starting: ${performance.now()}`); + let result = target.apply(thisArgument, argumentsList); + console.log(`Finished: ${performance.now()}`); + return result; + } + }; + return new Proxy(katanaToBeInjected, handler); + */ + return katanaToBeInjected; + }); + + interface IWeapon {} + interface ISamurai { + katana: IWeapon; + shuriken: IWeapon; + } + + @inversify.inject("IWeapon", "IWeapon") + class Samurai implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + @inversify.tagged("canThrow", false) katana: IWeapon, + @inversify.tagged("canThrow", true) shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + kernel.bind("Samurai").to(Samurai); + kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("IWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + + let throwable = inversify.tagged("canThrow", true); + let notThrowable = inversify.tagged("canThrow", false); + + @inversify.inject("IWeapon", "IWeapon") + class Samurai2 implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + @throwable("canThrow", false) katana: IWeapon, + @notThrowable("canThrow", true) shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + @inversify.inject("IWeapon", "IWeapon") + class Samurai3 implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + @inversify.named("strong") katana: IWeapon, + @inversify.named("weak") shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + kernel.bind("ISamurai").to(Samurai3); + kernel.bind("IWeapon").to(Katana).whenTargetNamed("strong"); + kernel.bind("IWeapon").to(Shuriken).whenTargetNamed("weak"); + + @inversify.inject("IWeapon", "IWeapon") + @inversify.paramNames("katana", "shuriken") + class Samurai4 implements ISamurai { + public katana: IWeapon; + public shuriken: IWeapon; + public constructor( + katana: IWeapon, + shuriken: IWeapon + ) { + this.katana = katana; + this.shuriken = shuriken; + } + } + + kernel.bind("ISamurai").to(Samurai4); + + kernel.bind("IWeapon").to(Katana).when((request: inversify.IRequest) => { + return request.target.name.equals("katana"); + }); + + kernel.bind("IWeapon").to(Shuriken).when((request: inversify.IRequest) => { + return request.target.name.equals("shuriken"); + }); + +} From 3192bfefde20e09bc6b19a4642c2456b520ce0b9 Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Fri, 11 Mar 2016 09:50:32 +0000 Subject: [PATCH 20/72] Update inversify.d.ts --- inversify/inversify.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 12a8c0111..fe2e3c1f7 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -73,7 +73,7 @@ declare namespace inversify { export interface IContext { kernel: IKernel; plan: IPlan; - addPlan(plan: IPlan); + addPlan(plan: IPlan): void; } export interface IPlan { From 867798fdbe89ef9f8d8db1a2920c89a5b0165d1b Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Fri, 11 Mar 2016 09:52:51 +0000 Subject: [PATCH 21/72] Update inversify-tests.ts --- inversify/inversify-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index c69bd064e..8d2d99d5c 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -19,7 +19,7 @@ module external_module_test { } interface IShuriken { - throw(); + throw(): string; } class Katana implements IKatana { From 880f9d3389dc201f26d2be74a3e57f8bea2a3d14 Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Fri, 11 Mar 2016 09:54:50 +0000 Subject: [PATCH 22/72] Update inversify-global-tests.ts --- inversify/inversify-global-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index 902f23aea..ab1ac4b11 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -12,7 +12,7 @@ module global_module_test { } interface IShuriken { - throw(); + throw(): string; } class Katana implements IKatana { From 0bbeafaf4fd58314e2ab53e11d7ee3aa76ab6bdd Mon Sep 17 00:00:00 2001 From: Strato Date: Fri, 11 Mar 2016 13:20:29 +0100 Subject: [PATCH 23/72] Added missing interface Windows.Storage.IStorageFolder2 Was introduced in WinRT 2.0. --- winrt/winrt.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index 687d7f83d..825e8186e 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -10017,7 +10017,7 @@ declare module Windows { removableDevices: Windows.Storage.StorageFolder; videosLibrary: Windows.Storage.StorageFolder; } - export class StorageFolder implements Windows.Storage.IStorageFolder, Windows.Storage.IStorageItem, Windows.Storage.Search.IStorageFolderQueryOperations, Windows.Storage.IStorageItemProperties { + export class StorageFolder implements Windows.Storage.IStorageFolder, Windows.Storage.IStorageFolder2, Windows.Storage.IStorageItem, Windows.Storage.Search.IStorageFolderQueryOperations, Windows.Storage.IStorageItemProperties { attributes: Windows.Storage.FileAttributes; dateCreated: Date; name: string; @@ -10063,6 +10063,7 @@ declare module Windows { getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number): Windows.Foundation.IAsyncOperation; getThumbnailAsync(mode: Windows.Storage.FileProperties.ThumbnailMode, requestedSize: number, options: Windows.Storage.FileProperties.ThumbnailOptions): Windows.Foundation.IAsyncOperation; static getFolderFromPathAsync(path: string): Windows.Foundation.IAsyncOperation; + tryGetItemAsync(name: string): Windows.Foundation.IAsyncOperation; } export class KnownFolders { static documentsLibrary: Windows.Storage.StorageFolder; @@ -10212,6 +10213,9 @@ declare module Windows { getItemsAsync(): Windows.Foundation.IAsyncOperation>; getItemsAsync(startIndex: number, maxItemsToRetrieve: number): Windows.Foundation.IAsyncOperation>; } + export interface IStorageFolder2 { + tryGetItemAsync(name: string): Windows.Foundation.IAsyncOperation; + } export interface IStorageFile extends Windows.Storage.IStorageItem, Windows.Storage.Streams.IRandomAccessStreamReference, Windows.Storage.Streams.IInputStreamReference { contentType: string; fileType: string; From bab4fd2882ec3c312a0829dfd900280e46cc1636 Mon Sep 17 00:00:00 2001 From: Markus Mauch Date: Fri, 11 Mar 2016 16:41:34 +0100 Subject: [PATCH 24/72] Added a lot of Metadata Typings --- microsoft-sdk-soap/microsoft-sdk-soap.d.ts | 179 ++++++++++++++++----- 1 file changed, 143 insertions(+), 36 deletions(-) diff --git a/microsoft-sdk-soap/microsoft-sdk-soap.d.ts b/microsoft-sdk-soap/microsoft-sdk-soap.d.ts index 217710aac..c3100e69b 100644 --- a/microsoft-sdk-soap/microsoft-sdk-soap.d.ts +++ b/microsoft-sdk-soap/microsoft-sdk-soap.d.ts @@ -2657,22 +2657,22 @@ declare module Sdk.Mdq export interface IEntityMetadata { - ActivityTypeMask: any; + ActivityTypeMask: number; Attributes: IAttributeMetadata[]; AutoCreateAccessTeams: any; AutoRouteToOwnerQueue: boolean; - CanBeInManyToMany: boolean; - CanBePrimaryEntityInRelationship: boolean; - CanBeRelatedEntityInRelationship: boolean; - CanCreateAttributes: boolean; - CanCreateCharts: boolean; - CanCreateForms: boolean; - CanCreateViews: boolean; - CanModifyAdditionalSettings: boolean; + CanBeInManyToMany: ManagedProperty; + CanBePrimaryEntityInRelationship: ManagedProperty; + CanBeRelatedEntityInRelationship: ManagedProperty; + CanCreateAttributes: ManagedProperty; + CanCreateCharts: ManagedProperty; + CanCreateForms: ManagedProperty; + CanCreateViews: ManagedProperty; + CanModifyAdditionalSettings: ManagedProperty; CanTriggerWorkflow: boolean; - Description: string; - DisplayCollectionName: string; - DisplayName: string; + Description: Label; + DisplayCollectionName: Label; + DisplayName: Label; IconLargeName: string; IconMediumName: string; IconSmallName: string; @@ -2680,60 +2680,145 @@ declare module Sdk.Mdq IsActivity: boolean; IsActivityParty: boolean; IsAIRUpdated: boolean; - IsAuditEnabled: boolean; + IsAuditEnabled: ManagedProperty; IsAvailableOffline: boolean; IsBusinessProcessEnabled: boolean; IsChildEntity: boolean; - IsConnectionsEnabled: boolean; + IsConnectionsEnabled: ManagedProperty; IsCustomEntity: boolean; - IsCustomizable: boolean; + IsCustomizable: ManagedProperty; IsDocumentManagementEnabled: boolean; - IsDuplicateDetectionEnabled: boolean; + IsDuplicateDetectionEnabled: ManagedProperty; IsEnabledForCharts: boolean; IsImportable: boolean; IsIntersect: boolean; - IsMailMergeEnabled: boolean; + IsMailMergeEnabled: ManagedProperty; IsManaged: boolean; - IsMappable: boolean; + IsMappable: ManagedProperty; IsQuickCreateEnabled: boolean; IsReadingPaneEnabled: boolean; IsRenameable: boolean; IsValidForAdvancedFind: boolean; - IsValidForQueue: boolean; - IsVisibleInMobile: boolean; + IsValidForQueue: ManagedProperty; + IsVisibleInMobile: ManagedProperty; IsVisibleInMobileClient: boolean; LogicalName: string; - ManyToManyRelationships: any; - ManyToOneRelationships: any; + ManyToManyRelationships: ManyToManyRelationshipMetadata; + ManyToOneRelationships: OneToManyRelationshipMetadata; MetadataId: string; ObjectTypeCode: number; - OneToManyRelationships: any; - OwnershipType: string; + OneToManyRelationships: OneToManyRelationshipMetadata; + OwnershipType: "BusinessOwned" | "BusinessParented" | "None OrganizationOwned" | "TeamOwned UserOwned"; PrimaryIdAttribute: string; PrimaryImageAttribute: string; PrimaryNameAttribute: string; - Privileges: any; + Privileges: SecurityPrivilegeMetadata[]; RecurrenceBaseEntityLogicalName: string; ReportViewName: string; SchemaName: string; } + export interface SecurityPrivilegeMetadata + { + CanBeBasic: boolean; + CanBeDeep: boolean; + CanBeEntityReference: boolean; + CanBeGlobal: boolean; + CanBeLocal: boolean; + CanBeParentEntityReference: boolean; + ExtensionData: boolean; + Name: string; + PrivilegeId: string; + PrivilegeType: "Append" | "AppendTo" | "Assign" | "Create" | "Delete" | "None" | "Read" | "Share" | "Write"; + } + + export interface OneToManyRelationshipMetadata + { + AssociatedMenuConfiguration: AssociatedMenuConfiguration; + CascadeConfiguration: CascadeConfiguration; + HasChanged: any; + IntroducedVersion: any; + IsCustomizable: ManagedProperty; + IsCustomRelationship: boolean; + IsHierarchical: any; + IsManaged: boolean; + IsValidForAdvancedFind: boolean; + MetadataId: string; + ReferencedAttribute: string; + ReferencedEntity: string; + ReferencingAttribute: string; + ReferencingEntity: string; + RelationshipType: string; + SchemaName: string; + SecurityTypes: any; + } + + export interface CascadeConfiguration + { + Assign: CascadeType; + Delete: CascadeType; + ExtensionData: CascadeType; + Merge: CascadeType; + Reparent: CascadeType; + Share: CascadeType; + Unshare: CascadeType; + } + + export type CascadeType = "Active" | "Cascade" | "NoCascade" | "UserOwned"; + + export interface ManyToManyRelationshipMetadata + { + Entity1AssociatedMenuConfiguration: AssociatedMenuConfiguration; + Entity1IntersectAttribute: string; + Entity1LogicalName: string; + Entity2AssociatedMenuConfiguration: AssociatedMenuConfiguration; + Entity2IntersectAttribute: string; + Entity2LogicalName: string; + HasChanged: boolean; + IntersectEntityName: string; + IntroducedVersion: any; + IsCustomizable: ManagedProperty; + IsCustomRelationship: boolean; + IsManaged: boolean; + IsValidForAdvancedFind: boolean; + MetadataId: string; + RelationshipType: RelationshipType; + SchemaName: string; + SecurityTypes: SecurityType; + } + + export interface AssociatedMenuConfiguration + { + Behavior: AssociatedMenuBehavior; + Group: AssociatedMenuGroup; + Label: Label; + Order: number; + } + + export type AssociatedMenuBehavior = "DoNotDisplay" | "UseCollectionName" | "UseLabel"; + + export type AssociatedMenuGroup = "Details" | "Marketing" | "Sales" | "Service"; + + export type RelationshipType = "Default" | "ManyToManyRelationship" | "OneToManyRelationship"; + + export type SecurityType = "Append" | "Inheritance" | "None" | "ParentChild" | "Pointer"; + export interface IAttributeMetadata { - AttributeOf: any; - AttributeType: any; - AttributeTypeName: string; + AttributeOf: string; + AttributeType: "Customer" | "DateTime" | "Decimal" | "Double" | "EntityName" | "Integer" | "Lookup" | "ManagedProperty" | "Memo" | "Money" | "Owner" | "PartyList" | "Picklist" | "State" | "Status" | "Uniqueidentifier" | "Virtual" + AttributeTypeName: "BigIntType" | "BooleanType" | "CalendarRulesType" | "CustomerType" | "DateTimeType" | "DecimalType" | "DoubleType" | "EntityNameType" | "ImageType" | "IntegerType" | "LookupType" | "ManagedPropertyType" | "MemoType" | "MoneyType" | "OwnerType" | "PartyListType" | "PicklistType" | "StateType StatusType" | "StringType" | "UniqueidentifierType" | "VirtualType"; CalculationOf: any; CanBeSecuredForCreate: boolean; CanBeSecuredForRead: boolean; CanBeSecuredForUpdate: boolean; - CanModifyAdditionalSettings: boolean; + CanModifyAdditionalSettings: ManagedProperty; ColumnNumber: number; DefaultFormValue: any; DefaultValue: any; DeprecatedVersion: any; - Description: string; - DisplayName: string; + Description: Label; + DisplayName: Label; EntityLogicalName: string; Format: any; FormatName: string; @@ -2741,13 +2826,13 @@ declare module Sdk.Mdq IntroducedVersion: any; IsAuditEnabled: boolean; IsCustomAttribute: boolean; - IsCustomizable: boolean; + IsCustomizable: ManagedProperty; IsManaged: boolean; IsPrimaryId: boolean; IsPrimaryName: boolean; - IsRenameable: boolean; + IsRenameable: ManagedProperty; IsSecured: boolean; - IsValidForAdvancedFind: boolean; + IsValidForAdvancedFind: ManagedProperty; IsValidForCreate: boolean; IsValidForRead: boolean; IsValidForUpdate: boolean; @@ -2760,12 +2845,34 @@ declare module Sdk.Mdq OptionSet: any; Precision: any; PrecisionSource: any; - RequiredLevel: any; + RequiredLevel: ManagedProperty; SchemaName: string; Targets: string[]; YomiOf: any; } + export interface ManagedProperty + { + CanBeChanged: boolean; + ManagedPropertyLogicalName: string; + Value: T; + } + + export interface Label + { + LocalizedLabels: LocalizedLabel[]; + UserLocalizedLabel: LocalizedLabel; + } + + export interface LocalizedLabel + { + Label: string; + LangaugeCode: number; + MetadataId: string; + HasChanged: boolean; + IsManaged: boolean; + } + module ValueEnums { export enum OwnershipType @@ -2860,4 +2967,4 @@ declare module Sdk.Mdq } declare module Sdk.Mdq.ValueEnums -{ } +{ } \ No newline at end of file From 6a7b75abc6668b1cd9c5a9fc1cc00bfcb04ff535 Mon Sep 17 00:00:00 2001 From: "Barth, Chris" Date: Tue, 1 Mar 2016 13:43:09 -0500 Subject: [PATCH 25/72] Update winston definitions for v2.2.x --- winston/winston-tests.ts | 4 +-- winston/winston.d.ts | 63 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/winston/winston-tests.ts b/winston/winston-tests.ts index 0147af581..46a00e4da 100644 --- a/winston/winston-tests.ts +++ b/winston/winston-tests.ts @@ -158,9 +158,9 @@ profiler.start = new Date(); let testRewriter : winston.MetadataRewriter; testRewriter = function(level: string, msg: string, meta: any) { return meta; -} +}; -winston.addRewriter(testRewriter); +logger.rewriters.push(testRewriter); /** * New Logger instances with transports tests: */ diff --git a/winston/winston.d.ts b/winston/winston.d.ts index 0dc80a57c..2cc9f10d2 100644 --- a/winston/winston.d.ts +++ b/winston/winston.d.ts @@ -7,6 +7,10 @@ /// +///****************** +/// Winston v2.2.x +///****************** + declare module "winston" { export var transports: Transports; export var Transport: TransportStatic; @@ -15,6 +19,8 @@ declare module "winston" { export var loggers: ContainerInstance; export var defaultLogger: LoggerInstance; + export var exception: Exception; + export var exitOnError: boolean; export var level: string; @@ -46,17 +52,65 @@ declare module "winston" { export function addColors(target: any): any; export function setLevels(target: any): any; export function cli(): LoggerInstance; - export function addRewriter(rewriter: MetadataRewriter): void; + export function close(): void; + + export interface ExceptionProcessInfo { + pid: number; + uid?: number; + gid?: number; + cwd: string; + execPath: string; + version: string; + argv: string; + memoryUsage: NodeJS.MemoryUsage; + } + + export interface ExceptionOsInfo { + loadavg: [number, number, number]; + uptime: number; + } + + export interface ExceptionTrace { + column: number; + file: string; + "function": string; + line: number; + method: string; + native: boolean; + } + + export interface ExceptionAllInfo { + date: Date; + process: ExceptionProcessInfo; + os: ExceptionOsInfo; + trace: Array; + stack: Array; + } + + export interface Exception { + getAllInfo(err: Error): ExceptionAllInfo; + getProcessInfo(): ExceptionProcessInfo; + getOsInfo(): ExceptionOsInfo; + getTrace(err: Error): Array; + } export interface MetadataRewriter { (level: string, msg: string, meta: any): any; } + export interface MetadataFilter { + (level: string, msg: string, meta: any): string | {msg: any; meta: any;}; + } + export interface LoggerStatic { new (options?: LoggerOptions): LoggerInstance; } export interface LoggerInstance extends NodeJS.EventEmitter { + rewriters: Array; + filters: Array; + transports: Array; + extend(target: any): LoggerInstance; log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; @@ -81,7 +135,6 @@ declare module "winston" { handleExceptions(...transports: TransportInstance[]): void; unhandleExceptions(...transports: TransportInstance[]): void; add(transport: TransportInstance, options?: TransportOptions, created?: boolean): LoggerInstance; - addRewriter(rewriter: MetadataRewriter): void; clear(): void; remove(transport: TransportInstance): LoggerInstance; startTimer(): ProfileHandler; @@ -129,6 +182,7 @@ declare module "winston" { export interface FileTransportInstance extends TransportInstance { new (options?: FileTransportOptions): FileTransportInstance; + close(): void; } export interface HttpTransportInstance extends TransportInstance { @@ -269,10 +323,7 @@ declare module "winston" { start?: number; from?: Date; until?: Date; - /** - * 'asc' or 'desc' - */ - order?: string; + order?: "asc" | "desc"; fields: any; } From bd8fd111713a5db5be0796f8ea27ec4d1cd3a37e Mon Sep 17 00:00:00 2001 From: Anton Vasin Date: Fri, 11 Mar 2016 22:06:44 +0300 Subject: [PATCH 26/72] Correct export --- svgjs/svgjs.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/svgjs/svgjs.d.ts b/svgjs/svgjs.d.ts index c04f19536..4356d340e 100644 --- a/svgjs/svgjs.d.ts +++ b/svgjs/svgjs.d.ts @@ -7,8 +7,6 @@ // TODO sets // TODO gradients -declare var SVG:svgjs.Library; - declare module svgjs { export interface LinkedHTMLElement extends HTMLElement { @@ -272,6 +270,7 @@ declare module svgjs { } } +declare var SVG:svgjs.Library; declare module "svg.js" { - export = svgjs + export = SVG } From 7f75d6836a78e0eb6d2d224290448422d49b545e Mon Sep 17 00:00:00 2001 From: Dan Chao Date: Fri, 11 Mar 2016 14:30:28 -0800 Subject: [PATCH 27/72] add xdomain typings --- xdomain/xdomain-tests.ts | 14 +++++++++++ xdomain/xdomain.d.ts | 52 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 xdomain/xdomain-tests.ts create mode 100644 xdomain/xdomain.d.ts diff --git a/xdomain/xdomain-tests.ts b/xdomain/xdomain-tests.ts new file mode 100644 index 000000000..303fa15fe --- /dev/null +++ b/xdomain/xdomain-tests.ts @@ -0,0 +1,14 @@ +/// + +xdomain.masters({ + 'http://abc.example.com': '/api/*' +}); + +xdomain.slaves({ + "http://xyz.example.com": "/proxy.html" +}); + +xdomain.debug = true; +xdomain.on("log", (msg) => console.log(msg)); +xdomain.on("timeout", () => console.log("timeout")); +xdomain.cookies.master = "MASTER"; diff --git a/xdomain/xdomain.d.ts b/xdomain/xdomain.d.ts new file mode 100644 index 000000000..8b8931007 --- /dev/null +++ b/xdomain/xdomain.d.ts @@ -0,0 +1,52 @@ +// Type definitions for xdomain v0.7.5 +// Project: http://jpillora.com/xdomain/ +// Definitions by: Dan Chao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare interface XDomainCookies { + master: string; + slave: string; +} + +declare interface IXDomain { + /** + * Will initialize as a master + * + * Each of the slaves must be defined as: origin: proxy file + * + * The slaves object is used as a list slaves to force one proxy file per origin. + * @param slaveObj + */ + slaves (slaveObj: Object): void; + /** + * Will initialize as a slave + * + * Each of the masters must be defined as: origin: path + * + * origin and path are converted to a regular expression by escaping all non-alphanumeric chars, then converting * into .* and finally wrapping it with ^ and $. path can also be a RegExp literal. + * + * Requests that do not match both the origin and the path regular expressions will be blocked. + * @param masterObj + */ + masters(masterObj: Object): void; + origin: string; + /** + * When true, XDomain will log actions to console + */ + debug: boolean; + /** + * event may be log, warn or timeout. When listening for log and warn events, handler with contain the message as + * the first parameter. The timeout event fires when an iframe exeeds the xdomain.timeout time limit. + * @param event + * @param handler + */ + on(event: "log"|"warn"|"timeout", handler: (message?: string) => any): void; + cookies: XDomainCookies; +} + +declare var xdomain: IXDomain; + +declare module "xdomain" { + export const xdomain: IXDomain; +} From b0017a10e1a6ae8df207a244c5b9f3c9a9b696f2 Mon Sep 17 00:00:00 2001 From: TANAKA Koichi Date: Sat, 12 Mar 2016 22:50:39 +0900 Subject: [PATCH 28/72] sequelize: add Sequelize.models property --- sequelize/sequelize-tests.ts | 1 + sequelize/sequelize.d.ts | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 0e9adfe5f..ee5ff016b 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -1157,6 +1157,7 @@ new Sequelize( 'sequelize', null, null, { } ); s.model( 'Project' ); +s.models['Project']; s.define( 'Project', { name : Sequelize.STRING } ); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 3b42f52b2..353de8bac 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -5395,6 +5395,9 @@ declare module "sequelize" { } interface QueryOptionsTransactionRequired { } + interface ModelsHashInterface { + [name: string]: Model; + } /** * This is the main class, the entry point to sequelize. To use it, you just need to @@ -5415,6 +5418,11 @@ declare module "sequelize" { */ Sequelize: SequelizeStatic; + /** + * Defined models. + */ + models: ModelsHashInterface; + /** * Returns the specified dialect. */ From 36bfd4fd3b8d588cf9472cc0f9e299bd93f81f8b Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 1 Mar 2016 22:41:12 +0500 Subject: [PATCH 29/72] lodash: added _.isWeakMap --- lodash/lodash-tests.ts | 31 +++++++++++++++++++++++++++++++ lodash/lodash.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index daf6ab099..afbad410d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -7170,6 +7170,37 @@ module TestIsUndefined { } } +// _.isWeakMap +module TestIsWeakMap { + { + let value: number|WeakMap; + + if (_.isWeakMap(value)) { + let result: WeakMap = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isWeakMap(any); + result = _(1).isWeakMap(); + result = _([]).isWeakMap(); + result = _({}).isWeakMap(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isWeakMap(); + result = _([]).chain().isWeakMap(); + result = _({}).chain().isWeakMap(); + } +} + // _.lt module TestLt { { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 5285b0e6f..02a32583a 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -12267,6 +12267,31 @@ declare module _ { isUndefined(): LoDashExplicitWrapper; } + //_.isWeakMap + interface LoDashStatic { + /** + * Checks if value is classified as a WeakMap object. + * + * @param value The value to check. + * @returns Returns true if value is correctly classified, else false. + */ + isWeakMap(value?: any): value is WeakMap; + } + + interface LoDashImplicitWrapperBase { + /** + * @see _.isSet + */ + isWeakMap(): boolean; + } + + interface LoDashExplicitWrapperBase { + /** + * @see _.isSet + */ + isWeakMap(): LoDashExplicitWrapper; + } + //_.lt interface LoDashStatic { /** @@ -18487,3 +18512,4 @@ declare module "lodash" { // Backward compatibility with --target es5 interface Set {} interface Map {} +interface WeakMap {} From 6a1fe33b3dc37e7aea339867aab63f0351575069 Mon Sep 17 00:00:00 2001 From: Dan Chao Date: Sat, 12 Mar 2016 09:13:02 -0800 Subject: [PATCH 30/72] formatting --- xdomain/xdomain.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xdomain/xdomain.d.ts b/xdomain/xdomain.d.ts index 8b8931007..dddab6f37 100644 --- a/xdomain/xdomain.d.ts +++ b/xdomain/xdomain.d.ts @@ -29,7 +29,7 @@ declare interface IXDomain { * Requests that do not match both the origin and the path regular expressions will be blocked. * @param masterObj */ - masters(masterObj: Object): void; + masters (masterObj: Object): void; origin: string; /** * When true, XDomain will log actions to console @@ -41,7 +41,7 @@ declare interface IXDomain { * @param event * @param handler */ - on(event: "log"|"warn"|"timeout", handler: (message?: string) => any): void; + on (event: "log"|"warn"|"timeout", handler: (message?: string) => any): void; cookies: XDomainCookies; } From 853365e033d99a788a4d4b45dadf0933acb33da2 Mon Sep 17 00:00:00 2001 From: Alex Godko Date: Sat, 12 Mar 2016 21:12:08 +0200 Subject: [PATCH 31/72] Change chrome.runtime.onConnectExternal type Change onConnectExternal type from RuntimeEvent to ExtensionConnectEvent according to https://developer.chrome.com/extensions/runtime#event-onConnectExternal and unsuccessuful compilation of my project :) --- chrome/chrome.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index fccb84895..357229920 100644 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -5312,7 +5312,7 @@ declare module chrome.runtime { * Fired when a connection is made from another extension. * @since Chrome 26. */ - var onConnectExternal: RuntimeEvent; + var onConnectExternal: ExtensionConnectEvent; /** Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. */ var onSuspend: RuntimeEvent; /** From 47b55b16b1717f9f6c7c57eff6eced7db6cf4d34 Mon Sep 17 00:00:00 2001 From: Scotty Waggoner Date: Sat, 12 Mar 2016 16:12:07 -0500 Subject: [PATCH 32/72] Update lokijs.d.ts Add export for the LokiIndexedAdapter --- lokijs/lokijs.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lokijs/lokijs.d.ts b/lokijs/lokijs.d.ts index 1e93bb370..5b6251a65 100644 --- a/lokijs/lokijs.d.ts +++ b/lokijs/lokijs.d.ts @@ -1187,3 +1187,13 @@ declare var LokiConstructor: { declare module "lokijs" { export = LokiConstructor; } + + +declare var LokiIndexedAdapterConstructor: { + new (filename: string): LokiIndexedAdapter; +}; + + +declare module "loki-indexed-adapter" { + export = LokiIndexedAdapterConstructor; +} From a0e7554a6d70a2d5e9d3329799e5feb84769dd54 Mon Sep 17 00:00:00 2001 From: vvakame Date: Fri, 11 Mar 2016 00:12:57 +0900 Subject: [PATCH 33/72] rename lodash-tests-3.10.ts -> lodash-3.10-tests.ts --- lodash/{lodash-tests-3.10.ts => lodash-3.10-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename lodash/{lodash-tests-3.10.ts => lodash-3.10-tests.ts} (100%) diff --git a/lodash/lodash-tests-3.10.ts b/lodash/lodash-3.10-tests.ts similarity index 100% rename from lodash/lodash-tests-3.10.ts rename to lodash/lodash-3.10-tests.ts From 441e0ac7ce515175ddd1f0e4ea3de5f965d4c87c Mon Sep 17 00:00:00 2001 From: jonathanfishbein1 Date: Sat, 12 Mar 2016 22:43:29 -0500 Subject: [PATCH 34/72] Change return type of compe and seq functions to Function from void --- async/async.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/async/async.d.ts b/async/async.d.ts index 543b3751d..b266786b6 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -127,8 +127,8 @@ interface Async { doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void; - compose(...fns: Function[]): void; - seq(...fns: Function[]): void; + compose(...fns: Function[]): Function; + seq(...fns: Function[]): Function; applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; From 3ed9912c373bc32c0ccb9a4e8f9a44428ffb8bfc Mon Sep 17 00:00:00 2001 From: Victor Jacobs Date: Sun, 13 Mar 2016 14:03:17 +0100 Subject: [PATCH 35/72] Add 'awaitWriteFinish' option to Chokidar --- chokidar/chokidar.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/chokidar/chokidar.d.ts b/chokidar/chokidar.d.ts index 6a417ca72..be5dd4081 100644 --- a/chokidar/chokidar.d.ts +++ b/chokidar/chokidar.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chokidar 1.0.0 +// Type definitions for chokidar 1.4.3 // Project: https://github.com/paulmillr/chokidar // Definitions by: Stefan Steinhart // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -13,6 +13,7 @@ declare module "fs" add(filesDirsOrGlobs:Array):void; unwatch(fileDirOrGlob:string):void; unwatch(filesDirsOrGlobs:Array):void; + getWatched():any; } } @@ -33,10 +34,11 @@ declare module "chokidar" binaryInterval?:number; ignorePermissionErrors?:boolean; atomic?:boolean; + awaitWriteFinish?:any; } import fs = require("fs"); - function watch( fileDirOrGlob:string, options?:WatchOptions ):fs.FSWatcher; - function watch( filesDirsOrGlobs:Array, options?:WatchOptions ):fs.FSWatcher; + function watch(fileDirOrGlob:string, options?:WatchOptions):fs.FSWatcher; + function watch(filesDirsOrGlobs:Array, options?:WatchOptions):fs.FSWatcher; } From 0ba0d7058d2406e3314ccee7a4ae9ccdb0f3ae21 Mon Sep 17 00:00:00 2001 From: David Pfeffer Date: Sun, 13 Mar 2016 11:33:17 -0400 Subject: [PATCH 36/72] Exposed json wrapper for customization by user --- signalr/signalr.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 5f605eb5e..617fa84eb 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -169,12 +169,18 @@ declare namespace SignalR { protocol: string; host: string; } + + interface JsonConverter { + stringify: (o: any) => string; + parse: (str: string) => any; + } interface Connection { clientProtocol: string; ajaxDataType: string; contentType: string; id: string; + json: JsonConverter; logging: boolean; url: string; qs: string | Object; From 17547d7f0f89d98b34f2d6ee4cae6fec3f9e40c8 Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Sun, 13 Mar 2016 17:20:35 +0000 Subject: [PATCH 37/72] Update lokijs definition to latest v1.3.16 --- lokijs/lokijs.d.ts | 1350 ++++++++++++++++++++++++++++---------------- 1 file changed, 866 insertions(+), 484 deletions(-) diff --git a/lokijs/lokijs.d.ts b/lokijs/lokijs.d.ts index 1e93bb370..980c6750d 100644 --- a/lokijs/lokijs.d.ts +++ b/lokijs/lokijs.d.ts @@ -3,7 +3,7 @@ // Definitions by: TeamworkGuy2 // Definitions: https://github.com/borisyankov/DefinitelyTyped -// NOTE: definition last updated (2015-6-6) based on latest code as of https://github.com/techfort/LokiJS/commit/4ffdda188c59ac06b760575b4ca41ad591ca8b0d +// NOTE: definition last updated (2016-3-13) based on latest code as of https://github.com/techfort/LokiJS/commit/3d2cf9546cd22556444deeabc4df314f227ecf5c /** LokiJS * A lightweight document oriented javascript database @@ -17,45 +17,50 @@ * @param {object} options - config object */ interface Loki extends LokiEventEmitter { - filename: string; + // autosave support (disabled by default) + autosave: boolean; + autosaveInterval: number; // milliseconds between auto-saves + autosaveHandle: number; // ID from setInterval(...) collections: LokiCollection[]; databaseVersion: number; engineVersion: number; - // autosave support (disabled by default) - // pass autosave: true, autosaveInterval: 6000 in options to set 6 second autosave - autosave: boolean; - autosaveInterval: number; - autosaveHandle: number; // from setInterval() call + ENV: string;/*NODEJS, CORDOVA, BROWSER*/ + events: { [id: string]: ((...args: any[]) => void)[] }; /*{ + 'init': ((...args) => void)[]; + 'loaded': ((...args) => void)[]; + 'flushChanges': ((...args) => void)[]; + 'close': ((...args) => void)[]; + 'changes': ((...args) => void)[]; + 'warning': ((...args) => void)[]; + };*/ + filename: string; options: LokiConfigureOptions; - // currently keeping persistenceMethod and persistenceAdapter as loki level properties that - // will not or cannot be deserialized. You are required to configure persistence every time - // you instantiate a loki object (or use default environment detection) in order to load the database anyways. + persistenceAdapter: LokiPersistenceInterface; // persistenceMethod could be 'fs', 'localStorage', or 'adapter' // this is optional option param, otherwise environment detection will be used // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option. - persistenceMethod: string; - // retain reference to optional (non-serializable) persistenceAdapter 'instance' - persistenceAdapter: LokiPersistenceInterface; - ENV: string; - events: { - 'init': any[]; - 'flushChanges': any[]; - 'close': any[]; - 'changes': any[]; - 'warning': any[]; - }; + persistenceMethod: string; /*'fs', 'localStorage', 'adapter'*/ + verbose: boolean; new (filename: string, options: LokiConfigureOptions): Loki; + // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. + // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. + getIndexedAdapter(): LokiPersistenceInterface; // require("./loki-indexed-adapter.js") + + /** configureOptions - allows reconfiguring database options + * * @param {object} options - configuration options to apply to loki db object * @param {boolean} initialConfig - (optional) if this is a reconfig, don't pass this */ configureOptions(options: LokiConfigureOptions, initialConfig?: boolean): void; /** anonym() - shorthand method for quickly creating and populating an anonymous collection. - * This collection is not referenced internally so upon losing scope it will be garbage collected. - * Example : var results = new loki().anonym(myDocArray).find({'age': {'$gt': 30} }); + * This collection is not referenced internally so upon losing scope it will be garbage collected. + * + * Example : var results = new loki().anonym(myDocArray).find({'age': {'$gt': 30} }); + * * @param {Array} docs - document array to initialize the anonymous collection with * @param {Array} indexesArray - (Optional) array of property names to index * @returns {Collection} New collection which you can query or chain @@ -74,7 +79,8 @@ interface Loki extends LokiEventEmitter { getName(): string; - /** serializeReplacer - used to prevent certain properties from being serialized, may return null */ + /** serializeReplacer - used to prevent certain properties from being serialized + */ serializeReplacer(key: "autosaveHandle", value: T): T; serializeReplacer(key: "persistenceAdapter", value: T): T; serializeReplacer(key: "constraints", value: T): T; @@ -87,17 +93,24 @@ interface Loki extends LokiEventEmitter { toJson(): string; /** loadJSON - inflates a loki database from a serialized JSON string + * * @param {string} serializedDb - a serialized loki database string * @param {object} options - apply or override collection level settings */ - loadJSON(serializedDb: string, options: { [id: string]: { inflate?: (a: any, b: any) => void; proto: any; } }): void; + loadJSON(serializedDb: string, options?: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }): void; + + /** loadJSONObject - inflates a loki database from a JS object + * + * @param {object} dbObject - a serialized loki database string + * @param {object} options - apply or override collection level settings + */ + loadJSONObject(dbObject: Loki, options?: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }): void; /** close(callback) - emits the close event with an optional callback. Does not actually destroy the db * but useful from an API perspective */ close(callback?: (...args: any[]) => void): void; - /**-------------------------+ | Changes API | +--------------------------*/ @@ -107,8 +120,9 @@ interface Loki extends LokiEventEmitter { */ /** generateChangesNotification() - takes all the changes stored in each - * collection and creates a single array for the entire database. If an array of names - * of collections is passed then only the included collections will be tracked. + * collection and creates a single array for the entire database. If an array of names + * of collections is passed then only the included collections will be tracked. + * * @param {array} optional array of collection names. No arg means all collections are processed. * @returns {array} array of changes * @see private method createChange() in Collection @@ -120,27 +134,40 @@ interface Loki extends LokiEventEmitter { */ serializeChanges(collectionNamesArray?: string[]): string; - /** clearChanges() - clears all the changes in all collections. */ + /** clearChanges() - clears all the changes in all collections. + */ clearChanges(): void; /** loadDatabase - Handles loading from file system, local storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * * @param {object} options - not currently used (remove or allow overrides?) * @param {function} callback - (Optional) user supplied async callback / error handler */ - loadDatabase(options: { [id: string]: { inflate?: (a: any, b: any) => void; proto: any; } }, callback: (err: Error | string, data: any) => void): void; + loadDatabase(options: { [collectionName: string]: { inflate?: (src: any, dst: any) => void; proto: any; } }, callback?: (err: any, data: any) => void): void; /** saveDatabase - Handles saving to file system, local storage, or adapter (indexeddb) - * This method utilizes loki configuration options (if provided) to determine which - * persistence method to use, or environment detection (if configuration was not provided). + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * * @param {object} options - not currently used (remove or allow overrides?) * @param {function} callback - (Optional) user supplied async callback / error handler */ - saveDatabase(callback: (err: Error) => void): void; + saveDatabase(callback?: (err: any) => void): void; - // alias - save(callback: (err: Error) => void): void; + // alias for saveDatabase + save(callback ?: (err: any) => void): void; + + /** deleteDatabase - Handles deleting a database from file system, local + * storage, or adapter (indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * @param {object} options - not currently used (remove or allow overrides?) + * @param {function} callback - user supplied async callback / error handler + */ + deleteDatabase(options: any, callback: (err: any, data: any) => void): void; /** autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database * @returns {boolean} - true if database has changed since last autosave, false if not. @@ -148,49 +175,63 @@ interface Loki extends LokiEventEmitter { autosaveDirty(): boolean; /** autosaveClearFlags - resets dirty flags on all collections. - * Called from saveDatabase() after db is saved. + * Called from saveDatabase() after db is saved. */ autosaveClearFlags(): void; - /** autosaveEnable - begin a javascript interval to periodically save the database. */ - autosaveEnable(): void; + /** autosaveEnable - begin a javascript interval to periodically save the database. + * + * @param {object} options - not currently used (remove or allow overrides?) + * @param {function} callback - (Optional) user supplied async callback + */ + autosaveEnable(options?: LokiConfigureOptions, callback?: (err: any) => void): void; - /** autosaveDisable - stop the autosave interval timer. */ + /** autosaveDisable - stop the autosave interval timer. + */ autosaveDisable(): void; - } -/** LokiEventEmitter is a minimalist version of EventEmitter. It enables any + + +/** + * LokiEventEmitter is a minimalist version of EventEmitter. It enables any * constructor that inherits EventEmitter to emit events and trigger * listeners that have been added to the event through the on(event, callback) method */ interface LokiEventEmitter { - /** @prop Events property is a hashmap, with each property being an array of callbacks */ - events: {} //{ [id: string]: ((...args) => void)[] }; + /** + * @prop Events property is a hashmap, with each property being an array of callbacks + */ + events: { [eventName: string]: ((...args: any[]) => void)[] }; new (): LokiEventEmitter; - /** @prop asyncListeners - boolean determines whether or not the callbacks associated with each event + /** + * @prop asyncListeners - boolean determines whether or not the callbacks associated with each event * should happen in an async fashion or not * Default is false, which means events are synchronous */ asyncListeners: boolean; - /** @prop on(eventName, listener) - adds a listener to the queue of callbacks associated to an event + /** + * @prop on(eventName, listener) - adds a listener to the queue of callbacks associated to an event * @returns {int} the index of the callback in the array of listeners for a particular event */ - on(eventName: string, listener: (...args: any[]) => void): (...args: any[]) => void; + on void>(eventName: string, listener: U): U; - /** @propt emit(eventName, data) - emits a particular event + /** + * @propt emit(eventName, data) - emits a particular event * with the option of passing optional parameters which are going to be processed by the callback * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters) * @param {string} eventName - the name of the event * @param {object} data - optional object passed with the event */ - emit(eventName: string, data: any): void; + emit(eventName: string, data?: any): void; - /** @prop remove() - removes the listener at position 'index' from the event 'eventName' */ + /** + * @prop remove() - removes the listener at position 'index' from the event 'eventName' + */ removeListener(eventName: string, listener: (...args: any[]) => void): void; } @@ -206,135 +247,184 @@ interface LokiEventEmitter { * localStorage for use in browser environment * defined as helper classes here so its easy and clean to use */ -interface LokiFsAdapter { - //fs; // require('fs'); + +interface LokiPersistenceInterface { + loadDatabase(dbname: string, callback: (dataOrErr: string | Error) => void): void; + saveDatabase(dbname: string, dbstring: string, callback: (resOrErr: void | Error) => void): void; + deleteDatabase(dbname: string, callback?: (resOrErr: void | Error) => void): void; + // optional + mode?: string; // 'reference' + // filename may seem redundant but loadDatabase will need to expect this same filename + exportDatabase?(filename: string, param: any, callback?: (err: any) => void): void; +} + + +/** constructor for fs + */ +interface LokiFsAdapter extends LokiPersistenceInterface { + fs: any; //require('fs'); /** loadDatabase() - Load data from file, will throw an error if the file does not exist * @param {string} dbname - the filename of the database to load * @param {function} callback - the callback to handle the result */ - loadDatabase(dbname: string, callback: (data: string | Error) => void): void; + loadDatabase(dbname: string, callback: (err: Error, data: string) => void): void; /** saveDatabase() - save data to file, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save * @param {string} dbname - the filename of the database to load * @param {function} callback - the callback to handle the result */ - saveDatabase(dbname: string, dbstring: string, callback: (error: any) => void): void; + saveDatabase(dbname: string, dbstring: string, callback: (err: any) => void): void; + + /** deleteDatabase() - delete the database file, will throw an error if the + * file can't be deleted + * @param {string} dbname - the filename of the database to delete + * @param {function} callback - the callback to handle the result + */ + deleteDatabase(dbname: string, callback: (resOrErr: void | Error) => void): void; } - - -/** constructor for local storage */ -interface LokiLocalStorageAdapter { +/** constructor for local storage + */ +interface LokiLocalStorageAdapter extends LokiPersistenceInterface { /** loadDatabase() - Load data from localstorage * @param {string} dbname - the name of the database to load * @param {function} callback - the callback to handle the result */ - loadDatabase(dbname: string, callback: (data: string | Error) => void): void; + loadDatabase(dbname: string, callback: (dataOrErr: string | Error) => void): void; /** saveDatabase() - save data to localstorage, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save * @param {string} dbname - the filename of the database to load * @param {function} callback - the callback to handle the result */ - saveDatabase(dbname: string, dbstring: string, callback: (error: Error) => void): void; + saveDatabase(dbname: string, dbstring: string, callback: (resOrErr: void | Error) => void): void; + + /** deleteDatabase() - delete the database from localstorage, will throw an error if it + * can't be deleted + * @param {string} dbname - the filename of the database to delete + * @param {function} callback - the callback to handle the result + */ + deleteDatabase(dbname: string, callback: (resOrErr: void | Error) => void): void; } /** Resultset class allowing chainable queries. Intended to be instanced internally. - * Collection.find(), Collection.where(), and Collection.chain() instantiate this. - * Example: - * mycollection.chain() - * .find({ 'doors' : 4 }) - * .where(function(obj) { return obj.name === 'Toyota' }) - * .data(); - * @param {Collection} collection - The collection which this Resultset will query against. - * @param {string} queryObj - Optional mongo-style query object to initialize resultset with. - * @param {function} queryFunc - Optional javascript filter function to initialize resultset with. - * @param {bool} firstOnly - Optional boolean used by collection.findOne(). + * Collection.find(), Collection.where(), and Collection.chain() instantiate this. + * + * Example: + * mycollection.chain() + * .find({ 'doors' : 4 }) + * .where(function(obj) { return obj.name === 'Toyota' }) + * .data(); */ interface LokiResultset { + // retain reference to collection we are querying against collection: LokiCollection; - searchIsChained: boolean; - filteredrows: string[]; // technically number[] (e.g. = Object.keys(this.collection.data)) filterInitialized: boolean; + filteredrows: string[]; // technically number[] (e.g. = Object.keys(this.collection.data)) + options: LokiResultsetOptions; + searchIsChained: boolean; - new (collection: LokiCollection, queryObj: LokiQuery, queryFunc: (obj: E) => boolean, firstOnly?: boolean): LokiResultset; - /** toJSON() - Override of toJSON to avoid circular references */ + /** + * @constructor + * @param {Collection} collection - The collection which this Resultset will query against. + * @param {Object} options - Object containing one or more options. + * @param {string} options.queryObj - Optional mongo-style query object to initialize resultset with. + * @param {function} options.queryFunc - Optional javascript filter function to initialize resultset with. + * @param {bool} options.firstOnly - Optional boolean used by collection.findOne(). + */ + new (collection: LokiCollection, options: LokiResultsetOptions): LokiResultset | E[]; + + /** reset() - Reset the resultset to its initial state. + * + * @returns {Resultset} Reference to this resultset, for future chain operations. + */ + reset(): LokiResultset; + + /** toJSON() - Override of toJSON to avoid circular references + */ toJSON(): LokiResultset; /** limit() - Allows you to limit the number of documents passed to next chain operation. - * A resultset copy() is made to avoid altering original resultset. + * A resultset copy() is made to avoid altering original resultset. + * * @param {int} qty - The number of documents to return. * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops. */ limit(qty: number): LokiResultset; /** offset() - Used for skipping 'pos' number of documents in the resultset. + * * @param {int} pos - Number of documents to skip; all preceding documents are filtered out. * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. */ offset(pos: number): LokiResultset; /** copy() - To support reuse of resultset in branched query situations. + * * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same. */ copy(): LokiResultset; - - // add branch() as alias of copy() + // alias of copy() branch(): LokiResultset; + /** + * transform() - executes a named collection transform or raw array of transform steps against the resultset. + * + * @param transform {string|array} : (Optional) name of collection transform or raw transform array + * @param parameters {object} : (Optional) object property hash of parameters, if the transform requires them. + * @returns {Resultset} : either (this) resultset or a clone of of this resultset (depending on steps) + */ + transform(transform?: string | any[], parameters?: any): LokiResultset; + /** sort() - User supplied compare function is provided two documents to compare. (chainable) - * Example: - * rslt.sort(function(obj1, obj2) { - * if (obj1.name === obj2.name) return 0; - * if (obj1.name > obj2.name) return 1; - * if (obj1.name < obj2.name) return -1; - * }); + * Example: + * rslt.sort(function(obj1, obj2) { + * if (obj1.name === obj2.name) return 0; + * if (obj1.name > obj2.name) return 1; + * if (obj1.name < obj2.name) return -1; + * }); + * * @param {function} comparefun - A javascript compare function used for sorting. * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. */ sort(comparefun: (a: E, b: E) => number): LokiResultset; /** simplesort() - Simpler, loose evaluation for user to sort based on a property name. (chainable) + * * @param {string} propname - name of property to sort by. * @param {bool} isdesc - (Optional) If true, the property will be sorted in descending order * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. */ simplesort(propname: string, isdesc?: boolean): LokiResultset; - /** compoundeval() - helper method for compoundsort(), performing individual object comparisons - * @param {array} properties - array of property names, in order, by which to evaluate sort order - * @param {object} obj1 - first object to compare - * @param {object} obj2 - second object to compare - * @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first - */ - compoundeval(properties: any[], obj1: any, obj2: any): number; - /** compoundsort() - Allows sorting a resultset based on multiple columns. - * Example : rs.compoundsort(['age', 'name']); to sort by age and then name (both ascending) - * Example : rs.compoundsort(['age', ['name', true]); to sort by age (ascending) and then by name (descending) + * Example : rs.compoundsort(['age', 'name']); to sort by age and then name (both ascending) + * Example : rs.compoundsort(['age', ['name', true]); to sort by age (ascending) and then by name (descending) + * * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. */ - compoundsort(properties: any[]): LokiResultset; + compoundsort(properties: ([string, boolean] | [string])[]): LokiResultset; /** calculateRange() - Binary Search utility method to find range/segment of values matching criteria. - * this is used for collection.find() and first find filter of resultset/dynview - * slightly different than get() binary search in that get() hones in on 1 value, - * but we have to hone in on many (range) - * @param {string} op - operation, such as $eq - * @param {string} prop - name of property to calculate range for - * @param {object} val - value to use for range calculation. - * @returns {array} [start, end] index array positions - */ + * this is used for collection.find() and first find filter of resultset/dynview + * slightly different than get() binary search in that get() hones in on 1 value, + * but we have to hone in on many (range) + * @param {string} op - operation, such as $eq + * @param {string} prop - name of property to calculate range for + * @param {object} val - value to use for range calculation. + * @returns {array} [start, end] index array positions + */ calculateRange(op: "$eq", prop: string, val: any): [number/*start*/, number/*end*/]; + calculateRange(op: "$dteq", prop: string, val: any): [number/*start*/, number/*end*/]; calculateRange(op: "$gt", prop: string, val: any): [number/*start*/, number/*end*/]; calculateRange(op: "$gte", prop: string, val: any): [number/*start*/, number/*end*/]; calculateRange(op: "$lt", prop: string, val: any): [number/*start*/, number/*end*/]; @@ -342,57 +432,78 @@ interface LokiResultset { calculateRange(op: string, prop: string, val: any): [number/*start*/, number/*end*/]; /** findOr() - oversee the operation of OR'ed query expressions. - * OR'ed expression evaluation runs each expression individually against the full collection, - * and finally does a set OR on each expression's results. - * Each evaluation can utilize a binary index to prevent multiple linear array scans. + * OR'ed expression evaluation runs each expression individually against the full collection, + * and finally does a set OR on each expression's results. + * Each evaluation can utilize a binary index to prevent multiple linear array scans. + * * @param {array} expressionArray - array of expressions * @returns {Resultset} this resultset for further chain ops. */ findOr(expressionArray: LokiQuery[]): LokiResultset; + $or(expressionArray: LokiQuery[]): LokiResultset; /** findAnd() - oversee the operation of AND'ed query expressions. - * AND'ed expression evaluation runs each expression progressively against the full collection, - * internally utilizing existing chained resultset functionality. - * Only the first filter can utilize a binary index. + * AND'ed expression evaluation runs each expression progressively against the full collection, + * internally utilizing existing chained resultset functionality. + * Only the first filter can utilize a binary index. + * * @param {array} expressionArray - array of expressions * @returns {Resultset} this resultset for further chain ops. */ findAnd(expressionArray: LokiQuery[]): LokiResultset; - - /** dotSubScan - helper function used for dot notation queries. */ - dotSubScan(root: any, property: string, fun: (a: any, b: any) => boolean, value: any): boolean; + $and(expressionArray: LokiQuery[]): LokiResultset; /** find() - Used for querying via a mongo-style query object. + * * @param {object} query - A mongo-style query object used for filtering current results. * @param {boolean} firstOnly - (Optional) Used by collection.findOne() * @returns {Resultset} this resultset for further chain ops. */ + //find(query: LokiQuery, firstOnly: boolean): E; //find(query?: any, firstOnly?: boolean): E[]; find(query: LokiQuery, firstOnly?: boolean): LokiResultset; /** where() - Used for filtering via a javascript filter function. + * * @param {function} fun - A javascript function used for filtering current results by. * @returns {Resultset} this resultset for further chain ops. */ where(fun: (obj: E) => boolean): LokiResultset; + /** count() - returns the number of documents in the resultset. + * + * @returns {number} The number of documents in the resultset. + */ + count(): number; + /** data() - Terminates the chain and returns array of filtered documents + * + * @param options {object} : allows specifying 'forceClones' and 'forceCloneMethod' options. + * options : + * forceClones {boolean} : Allows forcing the return of cloned objects even when + * the collection is not configured for clone object. + * forceCloneMethod {string} : Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', and 'shallow' + * * @returns {array} Array of documents in the resultset */ - data(): E[]; + data(options?: { forceClones?: string; forceCloneMethod?: string; }): E[]; /** update() - used to run an update operation on all documents currently in the resultset. - * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object. - * @returns {Resultset} this resultset for further chain ops. - */ - update(updateFunction: (obj: E) => U): LokiResultset; + * + * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object. + * @returns {Resultset} this resultset for further chain ops. + */ + update(updateFunction: (obj: E) => void): LokiResultset; /** remove() - removes all document objects which are currently in resultset from collection (as well as resultset) + * * @returns {Resultset} this (empty) resultset for further chain ops. */ remove(): LokiResultset; /** mapReduce() - data transformation via user supplied functions + * * @param {function} mapFunction - this function accepts a single document for you to transform and return * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction @@ -407,76 +518,94 @@ interface LokiResultset { * @param {function} (optional) mapFun - A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}] */ - eqJoin(joinData: T[]| LokiResultset, leftJoinKey: string | ((obj: T) => string), rightJoinKey: string | ((obj: E) => string)): LokiResultset<{ left: E; right: T; }>; - eqJoin(joinData: T[]| LokiResultset, leftJoinKey: string | ((obj: T) => string), rightJoinKey: string | ((obj: E) => string), mapFun?: (a: E, b: T) => U): LokiResultset; - - map(mapFun: (currentValue: E, index: number, array: E[]) => U): LokiResultset; + eqJoin(joinData: T[] | LokiResultset, leftJoinKey: string | ((obj: E) => string), rightJoinKey: string | ((obj: T) => string)): LokiResultset<{ left: E; right: T; }>; + eqJoin(joinData: T[] | LokiResultset, leftJoinKey: string | ((obj: E) => string), rightJoinKey: string | ((obj: T) => string), mapFun?: (a: E, b: T) => U): LokiResultset; + map(mapFun: (currentValue: E, index: number, array: E[]) => T): LokiResultset; } /** DynamicView class is a versatile 'live' view class which can have filters and sorts applied. - * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it - * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) - * Examples: - * var mydv = mycollection.addDynamicView('test'); // default is non-persistent - * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); - * mydv.applyFind({ 'doors' : 4 }); - * var results = mydv.data(); - * @param {Collection} collection - A reference to the collection to work against - * @param {string} name - The name of this dynamic view - * @param {boolean} persistent - (Optional) If true, the results will be copied into an internal array for read efficiency or binding to. + * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it + * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) + * + * Examples: + * var mydv = mycollection.addDynamicView('test'); // default is non-persistent + * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); + * mydv.applyFind({ 'doors' : 4 }); + * var results = mydv.data(); + * */ interface LokiDynamicView extends LokiEventEmitter { - name: string; + cachedresultset: LokiResultset; collection: LokiCollection; + events: { [id: string]: ((...args: any[]) => void)[] }; /*{ + 'rebuild': ((...args) => void)[]; + };*/ + // keep ordered filter pipeline + filterPipeline: LokiFilter[]; + minRebuildInterval: number; + name: string; + options: LokiDynamicViewOptions; persistent: boolean; + rebuildPending: boolean; resultset: LokiResultset; resultdata: E[]; resultsdirty: boolean; - cachedresultset: LokiResultset; // TODO type - // keep ordered filter pipeline - filterPipeline: { type: string/*'find', 'where'*/; value: LokiQuery | ((element: E, index: number, array: E[]) => boolean) }[]; // TODO type - // sorting member variables - we only support one active search, applied using applySort() or applySimpleSort() + // sorting member variables, we only support one active search, applied using applySort() or applySimpleSort() sortFunction: (a: E, b: E) => number; - sortCriteria: [string, boolean][]; // TODO type + sortCriteria: ([string, boolean] | [string])[]; sortDirty: boolean; - // for now just have 1 event for when we finally rebuilt lazy view - // once we refactor transactions, i will tie in certain transactional events - events: { - "rebuild": any[]; // TODO type - }; + sortPriority: string; // 'persistentSortPriority', 'passive' (will defer the sort phase until they call data(). most efficient overall), 'active' (will sort async whenever next idle. prioritizes read speeds) - new (collection: LokiCollection, name: string, persistent?: boolean): LokiDynamicView; + /** + * @constructor + * @param {Collection} collection - A reference to the collection to work against + * @param {string} name - The name of this dynamic view + * @param {object} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. + */ + new (collection: LokiCollection, name: string, options?: LokiDynamicViewOptions): LokiDynamicView; /** rematerialize() - intended for use immediately after deserialization (loading) - * This will clear out and reapply filterPipeline ops, recreating the view. - * Since where filters do not persist correctly, this method allows - * restoring the view to state where user can re-apply those where filters. + * This will clear out and reapply filterPipeline ops, recreating the view. + * Since where filters do not persist correctly, this method allows + * restoring the view to state where user can re-apply those where filters. + * * @param {Object} options - (Optional) allows specification of 'removeWhereFilters' option * @returns {DynamicView} This dynamic view for further chained ops. */ - rematerialize(options: { removeWhereFilters?: any/*boolean - if prop exists, action occurs*/; }): LokiDynamicView; + rematerialize(options?: { removeWhereFilters?: boolean; }): LokiDynamicView; /** branchResultset() - Makes a copy of the internal resultset for branched queries. - * Unlike this dynamic view, the branched resultset will not be 'live' updated, - * so your branched query should be immediately resolved and not held for future evaluation. + * Unlike this dynamic view, the branched resultset will not be 'live' updated, + * so your branched query should be immediately resolved and not held for future evaluation. + * + * @param {string|array} transform: Optional name of collection transform, or an array of transform steps + * @param {object} parameters: optional parameters (if optional transform requires them) * @returns {Resultset} A copy of the internal resultset for branched queries. */ - branchResultset(): LokiResultset; + branchResultset(transform?: string | any[], parameters?: any): LokiResultset; - /** toJSON() - Override of toJSON to avoid circular references */ + /** toJSON() - Override of toJSON to avoid circular references + */ toJSON(): LokiDynamicView; + /** removeFilters() - Used to clear pipeline and reset dynamic view to initial state. + * Existing options should be retained. + */ + removeFilters(): void; + /** applySort() - Used to apply a sort to the dynamic view + * * @param {function} comparefun - a javascript compare function used for sorting * @returns {DynamicView} this DynamicView object, for further chain ops. */ applySort(comparefun: (a: E, b: E) => number): LokiDynamicView; /** applySimpleSort() - Used to specify a property used for view translation. + * * @param {string} propname - Name of property by which to sort. * @param {boolean} isdesc - (Optional) If true, the sort will be in descending order. * @returns {DynamicView} this DynamicView object, for further chain ops. @@ -484,156 +613,279 @@ interface LokiDynamicView extends LokiEventEmitter { applySimpleSort(propname: string, isdesc?: boolean): LokiDynamicView; /** applySortCriteria() - Allows sorting a resultset based on multiple columns. - * Example : dv.applySortCriteria(['age', 'name']); to sort by age and then name (both ascending) - * Example : dv.applySortCriteria(['age', ['name', true]); to sort by age (ascending) and then by name (descending) - * Example : dv.applySortCriteria(['age', true], ['name', true]); to sort by age (descending) and then by name (descending) + * Example : dv.applySortCriteria(['age', 'name']); to sort by age and then name (both ascending) + * Example : dv.applySortCriteria(['age', ['name', true]); to sort by age (ascending) and then by name (descending) + * Example : dv.applySortCriteria(['age', true], ['name', true]); to sort by age (descending) and then by name (descending) + * * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations. */ - applySortCriteria(criteria: string | any[]): LokiDynamicView; + applySortCriteria(criteria: ([string, boolean] | [string])[]): LokiDynamicView; /** startTransaction() - marks the beginning of a transaction. + * * @returns {DynamicView} this DynamicView object, for further chain ops. */ startTransaction(): LokiDynamicView; /** commit() - commits a transaction. + * * @returns {DynamicView} this DynamicView object, for further chain ops. */ commit(): LokiDynamicView; /** rollback() - rolls back a transaction. + * * @returns {DynamicView} this DynamicView object, for further chain ops. */ rollback(): LokiDynamicView; - /** applyFind() - Adds a mongo-style query option to the DynamicView filter pipeline - * @param {object} query - A mongo-style query object to apply to pipeline - * @returns {DynamicView} this DynamicView object, for further chain ops. + /** Implementation detail. + * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID. + * + * @param {string|number} uid - The unique ID of the filter. + * @returns {number}: index of the referenced filter in the pipeline; -1 if not found. */ - applyFind(query: LokiQuery): LokiDynamicView; + _indexOfFilterWithId(uid: string | number): number; - /** applyWhere() - Adds a javascript filter function to the DynamicView filter pipeline - * @param {function} fun - A javascript filter function to apply to pipeline + /** Implementation detail. + * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset. + * + * @param {object} filter - The filter object. Refer to applyFilter() for extra details. + */ + _addFilter(filter: LokiFilter): void; + + /** reapplyFilters() - Reapply all the filters in the current pipeline. + * * @returns {DynamicView} this DynamicView object, for further chain ops. */ - applyWhere(fun: (obj: E) => boolean): LokiDynamicView; + reapplyFilters(): LokiDynamicView; + + /** applyFilter() - Adds or updates a filter in the DynamicView filter pipeline + * + * @param {object} filter - A filter object to add to the pipeline. + * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id } + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + applyFilter(filter: LokiFilter): LokiDynamicView; + + /** applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline + * + * @param {object} query - A mongo-style query object to apply to pipeline + * @param {string|number} uid - Optional: The unique ID of this filter, to reference it in the future. + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + applyFind(query: LokiQuery, uid?: string | number): LokiDynamicView; + + /** applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline + * + * @param {function} fun - A javascript filter function to apply to pipeline + * @param {string|number} uid - Optional: The unique ID of this filter, to reference it in the future. + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + applyWhere(fun: (obj: E) => boolean, uid?: string | number): LokiDynamicView; + + /** removeFilter() - Remove the specified filter from the DynamicView filter pipeline + * + * @param {string|number} uid - The unique ID of the filter to be removed. + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + removeFilter(uid: string | number): LokiDynamicView; + + /** count() - returns the number of documents representing the current DynamicView contents. + * + * @returns {number} The number of documents representing the current DynamicView contents. + */ + count(): number; /** data() - resolves and pending filtering and sorting, then returns document array as result. + * * @returns {array} An array of documents representing the current DynamicView contents. */ data(): E[]; - /** */ + /** queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. + * This event will throttle and queue a single rebuild event when batches of updates affect the view. + */ + queueRebuildEvent(): void; + + /** queueSortPhase : If the view is sorted we will throttle sorting to either : + * (1) passive - when the user calls data(), or + * (2) active - once they stop updating and yield js thread control + */ queueSortPhase(): void; - /** performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) */ - performSortPhase(): void; + /** performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) + */ + performSortPhase(options?: { suppressRebuildEvent?: boolean; }): void; /** evaluateDocument() - internal method for (re)evaluating document inclusion. - * Called by : collection.insert() and collection.update(). + * Called by : collection.insert() and collection.update(). + * * @param {int} objIndex - index of document to (re)run through filter pipeline. + * @param {bool} isNew - true if the document was just added to the collection. */ - evaluateDocument(objIndex: number): void; + evaluateDocument(objIndex: number, isNew?: boolean): void; - /** removeDocument() - internal function called on collection.delete() */ + /** removeDocument() - internal function called on collection.delete() + */ removeDocument(objIndex: number): void; /** mapReduce() - data transformation via user supplied functions + * * @param {function} mapFunction - this function accepts a single document for you to transform and return * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction */ - mapReduce(mapFunction: (value: E, index: number, array: E[]) => T, reduceFunction: (array: T[]) => U): U; - + mapReduce(mapFunction: (item: E, index: number, array: E[]) => T, reduceFunction: (array: T[]) => U): U; } /** Collection class that handles documents of same type - * @param {stirng} collection name - * @param {array} array of property names to be indicized - * @param {object} configuration object */ interface LokiCollection extends LokiEventEmitter { - // the name of the collection - name: string; - // the data held by the collection - data: E[]; - idIndex: number[]; // index of id - binaryIndices: { [id: string]: { name: string; dirty: boolean; values: number[] } }; // user defined indexes - constraints: { unique: { [id: string]: LokiUniqueIndex }; exact: { [id: string]: LokiExactIndex }; } - // the object type of the collection - objType: string; - // currentMaxId - change manually at your own peril! - maxId: number; - DynamicViews: LokiDynamicView[]; // TODO type - events: { - 'insert': any[]; - 'update': any[]; - 'pre-insert': any[]; - 'pre-update': any[]; - 'close': any[]; - 'flushbuffer': any[]; - 'error': any[]; - 'delete': any[]; - 'warning': any[]; + // option to observe objects and update them automatically, ignored if Object.observe is not supported + autoupdate: boolean; + // option to make event listeners async, default is sync + asyncListeners: boolean; + binaryIndices: { [id: string]: { name: string; dirty: boolean; values: number[] } }; + + cachedIndex: number[]; + cachedBinaryIndex: { [id: string]: { name: string; dirty: boolean; values: number[] } }; + cachedData: E[]; + // changes are tracked by collection and aggregated by the db + changes: LokiCollectionChange[]; + // default clone method (if enabled) is parse-stringify + cloneMethod: string; // 'parse-stringify' + // options to clone objects when inserting them + cloneObjects: boolean; + console: { + log: () => void; + warn: () => void; + error: () => void; }; + constraints: { + unique: { [id: string]: LokiUniqueIndex }; + exact: { [id: string]: LokiExactIndex }; + }; + data: E[]; // in autosave scenarios we will use collection level dirty flags to determine whether save is needed. // currently, if any collection is dirty we will autosave the whole database if autosave is configured. // defaulting to true since this is called from addCollection and adding a collection should trigger save dirty: boolean; - // changes are tracked by collection and aggregated by the db - changes: { name: string; operation: string/*'I', 'U', 'R'*/; obj: any }[]; - // private holders for cached data - cachedIndex: any; // TODO type - cachedBinaryIndex: any; // TODO type - cachedData: any; // TODO type - // options - transactional: boolean; - cloneObjects: boolean; - asyncListeners: boolean; + // disable track changes disableChangesApi: boolean; - setChangesApi: (enabled: boolean) => void; + DynamicViews: LokiDynamicView[]; + events: { [id: string]: ((...args: any[]) => void)[] }; /*{ + 'insert': ((...args) => void)[]; + 'update': ((...args) => void)[]; + 'pre-insert': ((...args) => void)[]; + 'pre-update': ((...args) => void)[]; + 'close': ((...args) => void)[]; + 'flushbuffer': ((...args) => void)[]; + 'error': ((...args) => void)[]; + 'delete': ((...args) => void)[]; + 'warning': ((...args) => void)[]; + };*/ + idIndex: number[]; + maxId: number; // currentMaxId - change manually at your own peril! + name: string; + // is collection transactional + transactional: boolean; + objType: string; + // transforms will be used to store frequently used query chains as a series of steps + // which itself can be stored along with the database. + transforms: { [id: string]: any }; + // unique contraints contain duplicate object references, so they are not persisted. + // we will keep track of properties which have unique contraint applied here, and regenerate on load + uniqueNames: string[]; - new (name: string, options?: LokiCollectionOptions): LokiCollection; + options: LokiCollectionOptions; + + // option to activate a cleaner daemon - clears "aged" documents at set intervals. + ttl: { + age: number; + ttlInterval: number; + daemon: number; + }; + + /** Collection class that handles documents of same type + * @constructor + * @param {string} collection name + * @param {array} array of property names to be indicized + * @param {object} configuration object + */ + new (name: string, options?: LokiCollectionOptions): LokiCollection; getChanges(): LokiCollectionChange[]; + setChangesApi(enabled: boolean): void; + flushChanges(): void; - byExample(template: any): { $and: any[] }; + observerCallback: (changes: { object: any }[]) => void; + + addAutoUpdateObserver(object: any): void; + + removeAutoUpdateObserver(object: any): void; + + addTransform(name: string, transform: any): void; + + setTransform(name: string, transform: any): void; + + removeTransform(name: string): void; + + byExample(template: any): { '$and': any[] }; findObject(template: any): E; findObjects(template: any): E[]; + /*----------------------------+ + | TTL daemon | + +----------------------------*/ + ttlDaemonFuncGen(): () => void; + + setTTL(age: number, interval: number): void; /*----------------------------+ | INDEXING | +----------------------------*/ - /** Ensure binary index on a certain field */ + /** + * create a row filter that covers all documents in the collection + */ + prepareFullDocIndex(): number[]; + + /** Ensure binary index on a certain field + */ ensureIndex(property: string, force?: boolean): void; - ensureUniqueIndex(field: string): void; + ensureUniqueIndex(field: string): LokiUniqueIndex; - /** Ensure all binary indices */ + /** Ensure all binary indices + */ ensureAllIndexes(force?: boolean): void; flagBinaryIndexesDirty(): void; - count(): number; + flagBinaryIndexDirty(index: string): void; - /** Rebuild idIndex */ + count(query?: LokiQuery): number; + + /** Rebuild idIndex + */ ensureId(): void; - /** Rebuild idIndex async with callback - useful for background syncing with a remote server */ + /** Rebuild idIndex async with callback - useful for background syncing with a remote server + */ ensureIdAsync(callback: () => void): void; - /** Each collection maintains a list of DynamicViews associated with it */ - addDynamicView(name: string, persistent?: boolean): LokiDynamicView; + /** Each collection maintains a list of DynamicViews associated with it + **/ + addDynamicView(name: string, options?: LokiDynamicViewOptions): LokiDynamicView; removeDynamicView(name: string): void; @@ -644,61 +896,78 @@ interface LokiCollection extends LokiEventEmitter { */ findAndUpdate(filterFunction: (obj: E) => boolean, updateFunction: (obj: E) => E): void; - /** generate document method - ensure objects have id and objType properties - * @param {object} the document to be inserted (or an array of objects) + /** generate document method - ensure object(s) have meta properties, clone it if necessary, etc. + * @param {object} doc: the document to be inserted (or an array of objects) * @returns document or documents (if passed an array of objects) */ insert(doc: E): E; insert(doc: E[]): E[]; + /** generate document method - ensure object has meta properties, clone it if necessary, etc. + * @param {object} the document to be inserted + * @returns document or 'undefined' if there was a problem inserting it + */ + insertOne(doc: E): E; + clear(): void; - /** Update method */ - update(doc: E): void; + /** Update method + */ + update(doc: E): E; + update(doc: E[]): void; - /** Add object to collection */ + /** Add object to collection + */ add(obj: E): E; removeWhere(query: ((obj: E) => boolean) | LokiQuery): void; removeDataOnly(): void; - /** delete wrapped */ - remove(doc: E | E[]| number | number[]): E; - + /** delete wrapped + */ + remove(doc: E): E; + remove(doc: number): E; + remove(doc: number[]): void; + remove(doc: E[]): void; /*---------------------+ | Finding methods | +----------------------*/ - /** Get by Id - faster than other methods because of the searching algorithm */ + /** Get by Id - faster than other methods because of the searching algorithm + */ get(id: number | string): E; - //get(id: number | string, returnPosition: true): [E, number]; - get(id: number | string, returnPosition: boolean): E |[E, number]; + get(id: number | string, returnPosition?: boolean): E | [E, number]; by(field: string): (value: any) => E; - by(field: string, value?: string): E; + by(field: string, value: string): E; - /** Find one object by index property, by property equal to value */ + /** Find one object by index property, by property equal to value + */ findOne(query: LokiQuery): E; /** Chain method, used for beginning a series of chained find() and/or view() operations * on a collection. + * + * @param {array} transform : Ordered array of transform step objects similar to chain + * @param {object} parameters: Object containing properties representing parameters to substitute + * @returns {Resultset} : (or data array if any map or join functions where called) */ - chain(): LokiResultset; + chain(transform?: string | any[], parameters?: any): LokiResultset; - /** Find method, api is similar to mongodb except for now it only supports one search parameter. + /** + * Find method, api is similar to mongodb except for now it only supports one search parameter. * for more complex queries use view() and storeView() */ - find(): LokiResultset; - find(query: LokiQuery): E[]; + find(): E[]; + find(query: LokiQuery): LokiResultset; /** Find object by unindexed field by property equal to value, * simply iterates and returns the first element matching the query */ findOneUnindexed(prop: string, value: any): E; - /** Transaction methods */ /** start the transation */ @@ -713,16 +982,18 @@ interface LokiCollection extends LokiEventEmitter { // async executor. This is only to enable callbacks at the end of the execution. async(fun: () => void, callback: () => void): void; - /** Create view function - filter */ + /** Create view function - filter + */ where(fun: (obj: E) => boolean): LokiResultset; - /** Map Reduce */ - mapReduce(mapFunction: (value: E, index: number, array: E[]) => T, reduceFunction: (previousValue: U, currentValue: T, index: number, array: T[]) => U): U; - - /** eqJoin - Join two collections on specified properties */ - eqJoin(joinData: T[]| LokiResultset, leftJoinProp: string | ((obj: T) => string), rightJoinProp: string | ((obj: E) => string)): LokiResultset<{ left: E; right: T; }>; - eqJoin(joinData: T[]| LokiResultset, leftJoinProp: string | ((obj: T) => string), rightJoinProp: string | ((obj: E) => string), mapFun?: (a: E, b: T) => U): LokiResultset; + /** Map Reduce + */ + mapReduce(mapFunction: (item: E, index: number, array: E[]) => U, reduceFunction: (array: U[]) => V): V; + /** eqJoin - Join two collections on specified properties + */ + eqJoin(joinData: T[] | LokiResultset, leftJoinProp: string | ((obj: E) => string), rightJoinProp: string | ((obj: T) => string)): LokiResultset<{ left: E; right: T; }>; + eqJoin(joinData: T[] | LokiResultset, leftJoinProp: string | ((obj: E) => string), rightJoinProp: string | ((obj: T) => string), mapFun?: (a: E, b: T) => U): LokiResultset; /* ------ STAGING API -------- */ /** stages: a map of uniquely identified 'stages', which hold copies of objects to be @@ -730,14 +1001,21 @@ interface LokiCollection extends LokiEventEmitter { */ stages: { [id: string]: any }; - /** create a stage and/or retrieve it */ - getStage(name: string): any; + /** create a stage and/or retrieve it + */ + getStage(name: string): E[]; - /** a collection of objects recording the changes applied through a commmitStage */ - commitLog: { timestamp: number; message: any; data: any }[]; + /** a collection of objects recording the changes applied through a commmitStage + */ + commitLog: { + timestamp: number; // timestamp (i.e. new Date().getTime()) + message: any; + data: E; + }[]; - /** create a copy of an object and insert it into a stage */ - stage(stageName: string, obj: T): T; + /** create a copy of an object and insert it into a stage + */ + stage(stageName: string, obj: E): E; /** re-attach all objects to the original collection, so indexes and views can be rebuilt * then create a message to be inserted in the commitlog @@ -762,80 +1040,187 @@ interface LokiCollection extends LokiEventEmitter { stdDev(field: string): number; - mode(field: string): number; + mode(field: string): string | number; median(field: string): number; } -/* -interface Utils { - copyProperties(src, dest): void; -} - -// Sort helper that support null and undefined -function ltHelper(prop1, prop2, equal?: boolean): boolean; - -function gtHelper(prop1, prop2, equal?: boolean): boolean; - -function sortHelper(prop1, prop2, desc?: boolean): number; - -function containsCheckFn(a: T[], b): (curr: T) => boolean; - -function containsCheckFn(a: string, b): (curr: string) => boolean; - -function containsCheckFn(a: T, b): (curr: string) => boolean; - -function clone(data: T, method?: string): T; - -function localStorageAvailable(): boolean; -*/ - - -/** General utils, including statistical functions */ -/* -function isDeepProperty(field: string): boolean; - -function parseBase10(num: number | string): number; - -function isNotUndefined(obj: any): boolean; - -function add(a: number, b: number): number; - -function sub(a: number, b: number): number; - -function median(values: number[]): number; - -function average(array: number[]): number; - -function standardDeviation(values: number[]): number; -*/ +/** comparison operators + * a is the value in the collection + * b is the query value + */ interface LokiOps { - // comparison operators - $eq: (a: any, b: any) => boolean; - $gt: (a: any, b: any) => boolean; - $gte: (a: any, b: any) => boolean; - $lt: (a: any, b: any) => boolean; - $lte: (a: any, b: any) => boolean; - $ne: (a: any, b: any) => boolean; - $regex: (a: string, b: RegExp) => boolean; - $in: (a: any, b: { indexOf: (value: any) => number }) => boolean; - $containsAny: (a: any, b: any[]| any) => boolean; - $contains: (a: any, b: any[]| any) => boolean; -} - -//declare var operators: LokiOps; - - -interface LokiDeepProperty { - (obj: any, property: string, isDeep?: boolean): any; + $eq(a: any, b: any): boolean; + $ne(a: any, b: any): boolean; + $dteq(a: any, b: any): boolean; + $gt(a: any, b: any): boolean; + $gte(a: any, b: any): boolean; + $lt(a: any, b: any): boolean; + $lte(a: any, b: any): boolean; + $in(a: any, b: { indexOf: (value: any) => boolean }): boolean; + $nin(a: any, b: { indexOf: (value: any) => boolean }): boolean; + $keyin(a: string, b: any): boolean; + $nkeyin(a: string, b: any): boolean; + $definedin(a: any, b: any): boolean; + $undefinedin(a: any, b: any): boolean; + $regex(a: any, b: RegExp | { test: (str: string) => boolean }): boolean; + $containsString(a: string | any, b: string): boolean; + $containsNone(a: any, b: any): boolean; + $containsAny(a: any, b: any | any[]): boolean; + $contains(a: any, b: any | any[]): boolean; + $type(a: any, b: any): boolean; + $size(a: any, b: any): boolean; + $len(a: any, b: any): boolean; + // field-level logical operators + // a is the value in the collection + // b is the nested query operation (for '$not') + // or an array of nested query operations (for '$and' and '$or') + $not(a: any, b: any): boolean; + $and(a: any, b: any[]): boolean; + $or(a: any, b: any[]): boolean; } -interface LokiBinarySearch { - (array: T[], item: T, fun: (a: T, b: T) => number): { found: boolean; index: number; }; +interface LokiKeyValueStore { + keys: K[]; + values: V[]; + + sort(a: any, b: any): number; + setSort(fun: (a: K, b: K) => number): void; + bs(): LokiBSonSort; + set(key: K, value: V): void; + get(key: K): V; +} + + +interface LokiUniqueIndex { + field: string; + keyMap: { [id: string]: E }; + lokiMap: { [id: number]: any }; + + new (uniqueField: string): LokiUniqueIndex; + + set(obj: E): void; + get(key: string): E; + byId(id: number): E; + update(obj: E): void; + remove(key: string): void; + clear(): void; +} + + +interface LokiExactIndex { + index: { [id: string]: E[] }; + field: string; + + new (exactField: string): LokiExactIndex + + /** add the value you want returned to the key in the index */ + set(key: string, val: E): void; + /** remove the value from the index, if the value was the last one, remove the key */ + remove(key: string, val: E): void; + /** get the values related to the key, could be more than one */ + get(key: string): E[]; + /** clear will zap the index */ + clear(key?: any): void; +} + + +interface LokiSortedIndex { + field: string; + keys: K[]; + values: V[][]; + + new (sortedField: string): LokiSortedIndex; + + // set the default sort + sort(a: any, b: any): number; + bs(): LokiBSonSort; + // and allow override of the default sort + setSort(fun: (a: any, b: any) => number): void; + // add the value you want returned to the key in the index + set(key: K, value: V): void; + // get all values which have a key == the given key + get(key: K): V[]; + // get all values which have a key < the given key + getLt(key: K): V[]; + // get all values which have a key > the given key + getGt(key: K): V[]; + // get all vals from start to end + getAll(key: K, start: number, end: number): V[]; + // just in case someone wants to do something smart with ranges + getPos(key: K): { found: boolean; index: number; }; + // remove the value from the index, if the value was the last one, remove the key + remove(key: K, value: V): void; + // clear will zap the index + clear(): void; +} + + +interface LokiConfigureOptions { + adapter?: LokiPersistenceInterface; + autoload?: boolean; + autoloadCallback?: (dataOrErr: any | Error) => void; + autosave?: boolean; + autosaveCallback?: (err: any) => void; + autosaveInterval?: number; // milliseconds between auto-saves + env?: string; /*'NODEJS', 'BROWSER', 'CORDOVA'*/ + persistenceMethod?: string; /*'fs', 'localStorage', 'adapter'*/ + verbose?: boolean; +} + + +interface LokiCollectionOptions { + asyncListeners?: boolean; + autoupdate?: boolean; + clone?: boolean; + cloneMethod?: string; + disableChangesApi?: boolean; + exact?: string[]; + indices?: string | string[]; + transactional?: boolean; + unique?: string | string[]; +} + + +interface LokiDynamicViewOptions { + minRebuildInterval?: number; + persistent?: boolean; + sortPriority: string; /*'active', 'passive'*/ +} + + +interface LokiResultsetOptions { + firstOnly?: boolean; + queryObj?: LokiQuery; + queryFunc?: (item: E) => boolean; +} + + +interface LokiQuery { +} + + +interface LokiFilter { + type: string; /*'find', 'where'*/ + val: LokiQuery | ((obj: E, index: number, array: E[]) => boolean); + uid: number | string; +} + + +interface LokiElementMetaData { + created: number; // unix style timestamp (i.e. new Date().getTime()) + revision: number; +} + + +interface LokiCollectionChange { + name: string; + operation: string;/*'I', 'R', 'U'*/ + obj: any; } @@ -844,140 +1229,82 @@ interface LokiBSonSort { } +/* +interface LokiUtils { + copyProperties(src: any, dest: any): void; + // used to recursively scan hierarchical transform step object for param substitution + resolveTransformObject(subObj: U, params: any, depth?: number): U; -interface LokiKeyValueStore { - keys: K[]; - values: V[]; - - sort(a: K, b: K): number; - setSort(fun: (a: K, b: K) => number): void; - bs(): LokiBSonSort; - set(key: K, value: V): void; - get(key: K): V; + // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution + resolveTransformParams(transform: U[], params: any): U[]; } +// Sort helper that support null and undefined +declare function ltHelper(prop1: any, prop2: any, equal?: boolean): boolean; +declare function gtHelper(prop1: any, prop2: any, equal?: boolean): boolean; +declare function sortHelper(prop1: any, prop2: any, desc?: boolean): number; -interface LokiUniqueIndex { - field: string; - keyMap: { [id: string]: E }; - lokiMap: { [id: number]: any }; // 'field' map +declare function doQueryOp(val: any, op: any): boolean; - new (uniqueField: string): LokiUniqueIndex; +declare function containsCheckFn(a: T[], b): (curr: T) => boolean; +declare function containsCheckFn(a: string, b): (curr: string) => boolean; +declare function containsCheckFn(a: T, b): (curr: string) => boolean; +*/ - set(obj: E): void; +/** General utils, including statistical functions + */ +/* +declare function isDeepProperty(field: string): boolean; - get(key: string): E; +declare function parseBase10(num: string | number): number; - byId(id: number): E; +declare function isNotUndefined(obj: any): boolean; - update(obj: E): void; +declare function add(a: string | number, b: string | number): number; - remove(key: string): void; +declare function sub(a: string | number, b: string | number): number; - clear(): void; -} +declare function median(values: number[]): number; + +declare function average(array: (string | number)[]); + +declare function standardDeviation(values: (string | number)[]): number; + +declare function deepProperty(obj: any, property: string, isDeep?: boolean): any; + +declare function binarySearch(array: U[], item: U, fun: (a: U, b: U) => number): { found: boolean; index: number; }; + +// compoundeval() - helper function for compoundsort(), performing individual object comparisons +// +// @param {array} properties - array of property names, in order, by which to evaluate sort order +// @param {object} obj1 - first object to compare +// @param {object} obj2 - second object to compare +// @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first +declare function compoundeval(properties: ([string, boolean] | [string])[], obj1: any, obj2: any): number; + +// dotSubScan - helper function used for dot notation queries. +declare function dotSubScan(root: any | any[], propPath: string[], fun: (root, value: V) => boolean, value: V): boolean; + +// making indexing opt-in... our range function knows how to deal with these ops : +//var indexedOpsList = ['$eq', '$dteq', '$gt', '$gte', '$lt', '$lte']; + +declare function clone(data: U, method?: string): U; // stage: 'parse-stringify', 'jquery-extend-deep', 'shallow' + +declare function cloneObjectArray(objarray: U[], method?: string): U; // stage: 'parse-stringify', 'jquery-extend-deep', 'shallow' + +declare function localStorageAvailable(): boolean; +*/ -interface LokiExactIndex { - index: { [id: string]: E[] }; - field: string; - - new (exactField: string): LokiExactIndex; - - // add the value you want returned to the key in the index - set(key: string, val: E): void; - - // remove the value from the index, if the value was the last one, remove the key - remove(key: string, val: E): void; - - // get the values related to the key, could be more than one - get(key: string): E[]; - - // clear will zap the index - clear(key?: any): void; -} - - - -interface LokiSortedIndex { - keys: K[]; - values: V[]; - - new (sortedField: string): LokiSortedIndex; - - // set the default sort - sort(a: K, b: K): number; - bs(): LokiBSonSort; - // and allow override of the default sort - setSort(fun: (a: K, b: K) => number): void; - // add the value you want returned to the key in the index - set(key: K, value: V): void; - // get all values which have a key == the given key - get(key: K): V | V[]; - // get all values which have a key < the given key - getLt(key: K): V[]; - // get all values which have a key > the given key - getGt(key: K): V[]; - - // get all vals from start to end - getAll(key: K, start: number, end: number): V[]; - // just in case someone wants to do something smart with ranges - getPos(key: K): boolean; - // remove the value from the index, if the value was the last one, remove the key - remove(key: K, value: V): void; - // clear will zap the index - clear(key?: any): void; -} - - -interface LokiPersistenceInterface { - loadDatabase: (fileName: string, func: (dbString: string) => void) => void; - saveDatabase: (fileName: string, content: string, func: () => void) => void; -} - - -interface LokiConfigureOptions { - env?: string/*'NODEJS', 'BROWSER', 'CORDOVA'*/; - persistenceMethod?: string/*'fs', 'localStorage'*/; - adapter?: LokiPersistenceInterface; - autoload?: any; - autoloadCallback?: (err: Error | string, data: any) => void; - autosave?: boolean; - autosaveInterval?: number; -} - - -interface LokiQuery { -} - - -interface LokiCollectionChange { - name: string; - operation: string/*'I', 'U', 'R'*/; - obj: any -} - - -interface LokiCollectionOptions { - transactional?: boolean; - clone?: boolean; - asyncListeners?: boolean; - disableChangesApi?: boolean; - indices?: string | string[]; -} - - - - -/* ==== loki-indexed-adapter.js ==== */ +/* ======== loki-indexed-adapter.js ======== */ interface LokiIndexedAdapter { app: string; - catalog: LokiCatalog; // TODO type + catalog: LokiCatalog; /** IndexedAdapter - Loki persistence adapter class for indexedDb. * This class fulfills abstract adapter interface which can be applied to other storage methods @@ -1005,10 +1332,10 @@ interface LokiIndexedAdapter { * @param {string} dbstring - the serialized db string to save. * @param {function} callback - (Optional) callback passed obj.success with true or false */ - saveDatabase(dbname: string, dbstring: string, callback?: (res: { success: boolean }) => void): void; + saveDatabase(dbname: string, dbstring: string, callback?: (err: Error | void) => void): void; // alias for saveDatabase - saveKey(dbname: string, dbstring: string, callback?: (res: { success: boolean }) => void): void; + saveKey(dbname: string, dbstring: string, callback?: (err: Error | void) => void): void; /** deleteDatabase() - Deletes a serialized db from the catalog. * @param {string} dbname - the name of the database to delete from the catalog. @@ -1030,7 +1357,6 @@ interface LokiIndexedAdapter { * @param {function} callback - (Optional) callback to accept result array. */ getCatalogSummary(callback: (entries: { app: string; key: string; size: number; }) => void): void; - } @@ -1057,24 +1383,30 @@ interface LokiCatalog { // Hide 'cursoring' and return array of { id: id, key: key } getAllKeys(callback: (data: any[]) => void): void; - } -/* ==== END loki-indexed-adapter.js ==== */ +/* ======== END loki-indexed-adapter.js ======== */ -/* ==== loki-crypted-file-adapter.js ==== */ -interface LokiCryptedFileAdapterEncryptResult { - cipher: string; - keyDerivation: string; - keyLength: number; - iterations: number; - iv: string; - salt: string; - value: string; -} +/* ======== loki-crypted-file-adapter.js ======== */ +/** + * @file lokiCryptedFileAdapter.js + * @author Hans Klunder + */ +/** require libs */ +//var fs = require('fs'); +//var cryptoLib = require('crypto'); +//var isError = require('util').isError; +/* The default Loki File adapter uses plain text JSON files. This adapter crypts the database string and wraps the result +* in a JSON including enough info to be able to decrypt it (except for the 'secret' of course !) +* +* The idea is that the 'secret' does not reside in your source code but is supplied by some other source (e.g. the user in node-webkit) +* +* The idea + encrypt/decrypt routines are borrowed from https://github.com/mmoulton/krypt/blob/develop/lib/krypt.js +* not using the krypt module to avoid third party dependencies +*/ interface LokiCryptedFileAdapter { secret: string; @@ -1084,56 +1416,69 @@ interface LokiCryptedFileAdapter { new (): LokiCryptedFileAdapter; /** setSecret() - set the secret to be used during encryption and decryption + * * @param {string} secret - the secret to be used */ setSecret(secret: string): void; /** loadDatabase() - Retrieves a serialized db string from the catalog. + * * @example - // LOAD - var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); - ptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user - var db = new loki('test.crypted', { adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' - db.loadDatabase(function(result) { - e.log('done'); - + // LOAD + var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); + cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user + var db = new loki('test.crypted', { adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' + db.loadDatabase(function(result) { + console.log('done'); + }); * * @param {string} dbname - the name of the database to retrieve. * @param {function} callback - callback should accept string param containing serialized db string. */ - loadDatabase(dbname: string, callback?: (res: string | Error) => void): void; + loadDatabase(dbname: string, callback: (decryptedDataOrErr: string | any) => void): void; /** + * @example - // SAVE : will save database in 'test.crypted' - cryptedFileAdapter = require('./lokiCryptedFileAdapter'); - ptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user - loki=require('lokijs'); - db = new loki('test.crypted',{ adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' - coll = db.addCollection('testColl'); - l.insert({test: 'val'}); - saveDatabase(); // could pass callback if needed for async complete - - ample - // if you have the krypt module installed you can use: - pt --decrypt test.crypted --secret mySecret - to view the contents of the database - + // SAVE : will save database in 'test.crypted' + var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); + cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user + var loki=require('lokijs'); + var db = new loki('test.crypted',{ adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' + var coll = db.addCollection('testColl'); + coll.insert({test: 'val'}); + db.saveDatabase(); // could pass callback if needed for async complete + + @example + // if you have the krypt module installed you can use: + krypt --decrypt test.crypted --secret mySecret + to view the contents of the database + * saveDatabase() - Saves a serialized db to the catalog. * * @param {string} dbname - the name to give the serialized database within the catalog. * @param {string} dbstring - the serialized db string to save. * @param {function} callback - (Optional) callback passed obj.success with true or false */ - saveDatabase(dbname: string, dbstring: string, callback?: (err?: any | LokiCryptedFileAdapterEncryptResult) => void): void; - + saveDatabase(dbname: string, dbstring: string, callback: (err: any) => void): void; } -/* ==== END loki-crypted-file-adapter.js ==== */ + + +interface LokiCryptedFileAdapterEncryptResult { + cipher: string; + keyDerivation: string; + keyLength: number; + iterations: number; + iv: string; + salt: string; + value: string; +} +/* ======== END loki-crypted-file-adapter.js ======== */ -/* ==== loki-angular.js ==== */ +/* ======== loki-angular.js ======== */ /* introduces a angular module named lokijs that returns the 'lokijs' module var module = angular.module('lokijs', []) .factory('Loki', function Loki() { @@ -1141,49 +1486,86 @@ interface LokiCryptedFileAdapter { }); return module; */ -/* ==== END loki-angular.js ==== */ +/* ======== END loki-angular.js ======== */ -/* ==== jquery-sync-adapter.js ==== */ +/* ======== jquery-sync-adapter.js ======== */ + +/** LokiJS JquerySyncAdapter + * A remote sync adapter example for LokiJS + * @author Joe Minichino + */ + /** this adapter assumes an object options is passed, * containing the following properties: * ajaxLib: jquery or compatible ajax library * save: { url: the url to save to, dataType [optional]: json|xml|etc., type [optional]: POST|GET|PUT} * load: { url: the url to load from, dataType [optional]: json|xml| etc., type [optional]: POST|GET|PUT } */ -interface JquerySyncAdapter { - options: { - ajaxLib: { - ajax(options: any): any; - }; - save: { - type?: string/*'GET', 'POST, 'DELETE', etc.*/; - dataType?: string/*'json', 'xml', etc.*/ - url?: string - }; - }; // TODO type +interface LokiJquerySyncAdapter { + options: LokiJquerySyncAdapterOptions - new (options: any): JquerySyncAdapter; + new (options: LokiJquerySyncAdapterOptions): LokiJquerySyncAdapter; - saveDatabase(name: any, data: any, callback?: (data: any, textStatus: string, jqXHR: XMLHttpRequest/*JQueryXHR*/) => any): void; - - loadDatabase(name: any, callback?: (data: any, textStatus: string, jqXHR: XMLHttpRequest/*JQueryXHR*/) => any): void; + saveDatabase(name: string, data: any, callback?: (data: any, textStatus: string, xhr: XMLHttpRequest) => any): void; + loadDatabase(name: string, callback?: (data: any, textStatus: string, xhr: XMLHttpRequest) => any): void; } -/* ==== END jquery-sync-adapter.js ==== */ +interface LokiJquerySyncAdapterOptions { + ajaxLib: { ajax(options: any): any; }; + save: { + url: any; + type?: string; /*'GET', 'POST, 'DELETE', etc.*/ + dataType?: string; /*'json', 'xml', etc.*/ + }; + load: { + url: any; + type?: string; /*'GET', 'POST, 'DELETE', etc.*/ + dataType?: string; /*'json', 'xml', etc.*/ + }; +} + + +interface LokiJquerySyncAdapterError extends Error { + name: string; // "JquerySyncAdapterError" + message: any; + + new (message: any): LokiJquerySyncAdapterError; +} +/* ======== END jquery-sync-adapter.js ======== */ + + + + +declare var LokiCryptedFileAdapterConstructor: { + new (): LokiCryptedFileAdapter; +} + +declare module "lokiCryptedFileAdapter" { + export = LokiCryptedFileAdapterConstructor; +} + + +declare var LokiIndexedAdapterConstructor: { + new (filename: string): LokiIndexedAdapter; +} + +declare module "loki-indexed-adapter" { + export = LokiIndexedAdapterConstructor; +} declare var LokiConstructor: { new (filename: string, options?: LokiConfigureOptions): Loki; + LokiOps: LokiOps; Collection: LokiCollection; KeyValueStore: LokiKeyValueStore; } - declare module "lokijs" { export = LokiConstructor; } From 2e0490d06c4368cb8ecce196e0f60c624fa9fc82 Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Sun, 13 Mar 2016 17:43:04 +0000 Subject: [PATCH 38/72] Create harmony-proxy.d.ts --- harmony-proxy/harmony-proxy.d.ts | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 harmony-proxy/harmony-proxy.d.ts diff --git a/harmony-proxy/harmony-proxy.d.ts b/harmony-proxy/harmony-proxy.d.ts new file mode 100644 index 000000000..c3893201b --- /dev/null +++ b/harmony-proxy/harmony-proxy.d.ts @@ -0,0 +1,37 @@ +// Type definitions for harmony-proxy 1.0.0 +// Project: https://www.npmjs.com/package/harmony-proxy +// Definitions by: Remo Jansen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module harmonyProxy { + type PropertyKey = string | number | symbol; + + interface ProxyHandler { + getPrototypeOf? (target: T): any; + setPrototypeOf? (target: T, v: any): boolean; + isExtensible? (target: T): boolean; + preventExtensions? (target: T): boolean; + getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor; + has? (target: T, p: PropertyKey): boolean; + get? (target: T, p: PropertyKey, receiver: any): any; + set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; + deleteProperty? (target: T, p: PropertyKey): boolean; + defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; + enumerate? (target: T): PropertyKey[]; + ownKeys? (target: T): PropertyKey[]; + apply? (target: T, thisArg: any, argArray?: any): any; + construct? (target: T, thisArg: any, argArray?: any): any; + } + + interface ProxyConstructor { + revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; + new (target: T, handler: ProxyHandler): T + } +} + +declare let Proxy: harmonyProxy.ProxyConstructor; + +declare module "harmony-proxy" { + let _Proxy: harmonyProxy.ProxyConstructor; + export = _Proxy; +} From 25d46c96646e9838d14aa7405a232fe79b3423e4 Mon Sep 17 00:00:00 2001 From: "Tom X. Tobin" Date: Sun, 13 Mar 2016 18:43:59 -0400 Subject: [PATCH 39/72] Update merge-stream typings for v1.0.0 --- merge-stream/merge-stream-tests.ts | 6 ++++++ merge-stream/merge-stream.d.ts | 11 ++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/merge-stream/merge-stream-tests.ts b/merge-stream/merge-stream-tests.ts index e0c744953..140013eb9 100644 --- a/merge-stream/merge-stream-tests.ts +++ b/merge-stream/merge-stream-tests.ts @@ -11,3 +11,9 @@ var merged = merge(stream1, stream2); var stream3 = new Stream(); merged.add(stream3); + +var stream4 = new Stream(); +var stream5 = new Stream(); +merged.add([stream4, stream5]); + +merged.isEmpty(); diff --git a/merge-stream/merge-stream.d.ts b/merge-stream/merge-stream.d.ts index 6dfffdb95..d2f8c756e 100644 --- a/merge-stream/merge-stream.d.ts +++ b/merge-stream/merge-stream.d.ts @@ -1,14 +1,15 @@ -// Type definitions for merge-stream +// Type definitions for merge-stream v1.0.0 // Project: https://github.com/grncdr/merge-stream -// Definitions by: Keita Kagurazaka -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Keita Kagurazaka , Tom X. Tobin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// declare module "merge-stream" { - interface IMergedStream extends NodeJS.ReadWriteStream { - add: (source: NodeJS.ReadableStream) => IMergedStream; + add(source: NodeJS.ReadableStream): IMergedStream; + add(source: NodeJS.ReadableStream[]): IMergedStream; + isEmpty(): boolean; } function merge(...streams: T[]): IMergedStream; From 91265f7398d3ef80a30997e62a4803a0a96fb9bc Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Sun, 13 Mar 2016 17:48:19 +0000 Subject: [PATCH 40/72] Create harmony-proxy-tests.ts Create harmony-proxy-global-test.ts Delete harmony-proxy-global-test.ts Update harmony-proxy.d.ts Update harmony-proxy-tests.ts Update harmony-proxy-tests.ts Update harmony-proxy-tests.ts Update harmony-proxy-tests.ts Update harmony-proxy-tests.ts --- harmony-proxy/harmony-proxy-tests.ts | 27 +++++++++++++++++++++++++++ harmony-proxy/harmony-proxy.d.ts | 2 -- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 harmony-proxy/harmony-proxy-tests.ts diff --git a/harmony-proxy/harmony-proxy-tests.ts b/harmony-proxy/harmony-proxy-tests.ts new file mode 100644 index 000000000..4c011d5fd --- /dev/null +++ b/harmony-proxy/harmony-proxy-tests.ts @@ -0,0 +1,27 @@ +/// + +import * as Proxy from "harmony-proxy"; + +interface IKatana { + use: () => void; +} + +class Katana implements IKatana { + public use() { + console.log("Used Katana!"); + } +} + +let handler = { + apply: function(target: any, thisArg: any, argArray: any) { + console.log(`Starting: ${performance.now()}`); + let result = target.apply(thisArg, argArray); + console.log(`Finished: ${performance.now()}`); + return result; + } +}; + +let katana = new Katana(); + +let katanaProxy = new Proxy(katana, handler); +katanaProxy.use(); diff --git a/harmony-proxy/harmony-proxy.d.ts b/harmony-proxy/harmony-proxy.d.ts index c3893201b..dba832c14 100644 --- a/harmony-proxy/harmony-proxy.d.ts +++ b/harmony-proxy/harmony-proxy.d.ts @@ -29,8 +29,6 @@ declare module harmonyProxy { } } -declare let Proxy: harmonyProxy.ProxyConstructor; - declare module "harmony-proxy" { let _Proxy: harmonyProxy.ProxyConstructor; export = _Proxy; From e2ccdcb1f55af692552746555d7a085e9da50974 Mon Sep 17 00:00:00 2001 From: bang Date: Mon, 14 Mar 2016 10:51:48 +0800 Subject: [PATCH 41/72] Update antd typings for v0.12.10 --- antd/antd.d.ts | 873 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 852 insertions(+), 21 deletions(-) diff --git a/antd/antd.d.ts b/antd/antd.d.ts index 96e473c54..ac23dcdc7 100644 --- a/antd/antd.d.ts +++ b/antd/antd.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Antd v0.12.8 +// Type definitions for Antd v0.12.10 // Project: http://ant.design // Definitions by: bang88 // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -11,42 +11,91 @@ declare namespace Antd { // Affix interface AffixProps extends React.Props { + /** + * 达到指定偏移量后触发 + */ offset?: number } + /** + * # Affix + * 将页面元素钉在可视范围。 + * ## 何时使用 + * 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 + * 页面可视范围过小时,慎用此功能以免遮挡页面内容。 + */ export class Affix extends React.Component{ } // Alert interface AlertProps extends React.Props { + /** + * 必选参数,指定警告提示的样式,有四种选择`success`、`info`、`warn`、`error` + */ type: string, + /**可选参数,默认不显示关闭按钮 */ closable?: boolean, + /**可选参数,自定义关闭按钮 */ closeText?: React.ReactNode, + /**必选参数,警告提示内容 */ message: React.ReactNode, + /**可选参数,警告提示的辅助性文字介绍 */ description?: React.ReactNode, + /**可选参数,关闭时触发的回调函数 */ onClose?: Function, + /**可选参数,是否显示辅助图标 */ showIcon?: boolean } + + + /** + * # Alert + * 警告提示,展现需要关注的信息。 + + * ## 何时使用 + + * - 当某个页面需要向用户显示警告的信息时。 + * - 非浮层的静态展现形式,始终展现,不会自动消失,用户可以点击关闭。 + * */ export class Alert extends React.Component{ } // Badge + /** + * #Badge + * + * 图标右上角的圆形徽标数字。 + + * ## 何时使用 + + * 一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。 + * + */ export class Badge extends React.Component{ } interface BadgeProps extends React.Props { + /** 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏*/ count: number, + /** 展示封顶的数字值*/ overflowCount?: number, + /** 不展示数字,只有一个小红点*/ dot?: boolean } // Button interface ButtonProps extends React.Props