diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 3a5e904f4..290a3c8ca 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -13,12 +13,15 @@ All definitions files include a header with the author and editors, so at some p * [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [angular-file-upload](https://github.com/danialfarid/angular-file-upload) (by [John Reilly](https://github.com/johnnyreilly)) * [angular-spinner](https://github.com/urish/angular-spinner) (by [Marcin Biegała](https://github.com/Biegal)) * [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular Hotkeys](https://github.com/chieffancypants/angular-hotkeys/) (by [Jason Zhao](https://github.com/jlz27)) * [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong)) * [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib)) * [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted)) +* [any-db](https://github.com/grncdr/node-any-db) (by [Rogier Schouten](https://github.com/rogier-schouten)) +* [any-db-transaction](https://github.com/grncdr/node-any-db-transaction) (by [Rogier Schouten](https://github.com/rogier-schouten)) * [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago)) * [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16)) * [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com)) @@ -45,6 +48,7 @@ All definitions files include a header with the author and editors, so at some p * [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby)) * [bucks](https://github.com/CyberAgent/bucks.js) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) +* [CanvasJS](http://canvasjs.com) (by [Mark Overholt](https://github.com/mover5)) * [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) * [Chroma.js](https://github.com/gka/chroma.js) (by [Sebastian Brückner](https://github.com/invliD)) @@ -85,6 +89,7 @@ All definitions files include a header with the author and editors, so at some p * [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428)) * [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/)) * [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov)) +* [FastClick](https://github.com/ftlabs/fastclick) (by [Shinnosuke Watanabe](https://github.com/shinnn)) * [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/)) * [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/)) * [Finch](https://github.com/stoodder/finchjs) (by [David Sichau](https://github.com/DavidSichau/)) @@ -128,13 +133,14 @@ All definitions files include a header with the author and editors, so at some p * [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) * [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) * [Highland](http://highlandjs.org/) (by [Bart van der Schoor](https://github.com/Bartvds/)) -* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) +* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee) and [Jeremy Hull](https://github.com/sourrust)) * [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn)) * [htmlparser2](https://github.com/fb55/htmlparser2/) (by [James Roland Cabresos](https://github.com/staticfunction)) * [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613)) * [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) +* [i18n-node](https://github.com/mashpie/i18n-node) (by [Maxime LUCE](https://github.com/SomaticIT)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) * [Imagemagick](http://github.com/rsms/node-imagemagick) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) @@ -212,6 +218,7 @@ All definitions files include a header with the author and editors, so at some p * [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) * [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) * [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) (by [Maxime LUCE](https://github.com/SomaticIT)) * [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki)) * [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/)) * [jsTree](http://www.jstree.com/) (by [Adam Pluciński](https://github.com/adaskothebeast)) @@ -231,6 +238,7 @@ All definitions files include a header with the author and editors, so at some p * [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek)) * [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig)) * [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising)) +* [Knockstrap](http://faulknercs.github.io/Knockstrap/) (by [Adam Pluciński](https://github.com/adaskothebeast)) * [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising)) * [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov)) * [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds)) @@ -274,14 +282,17 @@ All definitions files include a header with the author and editors, so at some p * [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici)) * [Node.js](http://nodejs.org/) (from TypeScript samples) * [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-azure](https://github.com/Azure/azure-sdk-for-node) (by [Andrew Gaspar](https://github.com/AndrewGaspar), [Anti Veeranna](https://github.com/antiveeranna) and [Maxime LUCE](https://github.com/SomaticIT)) * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) * [node-form](https://github.com/rsamec/form) (by [Roman Samec](https://github.com/rsamec)) * [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame)) * [nodeunit](https://github.com/caolan/nodeunit) (by [Jeff Goddard](https://github.com/jedigo)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) * [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-tar](https://github.com/npm/node-tar) (by [Maxime LUCE](https://github.com/SomaticIT)) * [node-uuid](https://github.com/broofa/node-uuid) (by [Jeff May](https://github.com/jeffmay)) * [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) +* [npm](https://github.com/npm/npm) (by [Maxime LUCE](https://github.com/SomaticIT)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) * [object-path](https://github.com/mariocasciaro/object-path) (by [Paulo Cesar](https://github.com/pocesar/)) @@ -291,6 +302,7 @@ All definitions files include a header with the author and editors, so at some p * [Optimist](https://github.com/substack/node-optimist) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) * [passport-facebook](https://github.com/jaredhanson/passport-facebook) (by [James Roland Cabresos](https://github.com/staticfunction/)) +* [passport-local](https://github.com/jaredhanson/passport-local) (by [Maxime LUCE](https://github.com/SomaticIT)) * [passport-strategy](https://github.com/jaredhanson/passport-strategy) (by [Lior Mualem](https://github.com/liorm)) * [pathwatcher](http://atom.github.io/node-pathwatcher/) (by [vvakame](https://github.com/vvakame)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) @@ -302,6 +314,7 @@ All definitions files include a header with the author and editors, so at some p * [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) * [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) * [Physijs](http://chandlerprall.github.io/Physijs/) (by [gyoh_k](https://github.com/gyohk)) +* [Pickadate.js](https://github.com/amsul/pickadate.js) (by [Adi Dahiya](https://github.com/adidahiya)) * [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments)) * [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) * [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) @@ -331,6 +344,7 @@ All definitions files include a header with the author and editors, so at some p * [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong)) * [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds)) * [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428)) +* [sendgrid](https://github.com/sendgrid/sendgrid-nodejs) (by [Maxime LUCE](https://github.com/SomaticIT)) * [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com)) * [ShellJS](http://shelljs.org) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [Showdown](https://github.com/coreyti/showdown) (by [Chris Bowdon](https://github.com/cbowdon)) @@ -349,9 +363,11 @@ All definitions files include a header with the author and editors, so at some p * [source-map](https://github.com/mozilla/source-map) (by [Morten Houston Ludvigsen](https://github.com/MortenHoustonLudvigsen)) * [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov)) * [sqlite3](https://github.com/mapbox/node-sqlite3) (by [Nick Malaguti](https://github.com/nmalaguti)) +* [stampit](https://github.com/ericelliott/stampit) (by [Vasyl Boroviak](https://github.com/koresar)) * [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame)) * [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone)) +* [stylus](https://github.com/LearnBoost/stylus) (by [Maxime LUCE](https://github.com/SomaticIT)) * [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Swiper](http://www.idangero.us/sliders/swiper) (by [Sebastián Galiano](https://github.com/sgaliano)) * [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/angular-file-upload/angular-file-upload-tests.ts b/angular-file-upload/angular-file-upload-tests.ts new file mode 100644 index 000000000..d59e65b4e --- /dev/null +++ b/angular-file-upload/angular-file-upload-tests.ts @@ -0,0 +1,47 @@ +/// + +module controllers { + + "use strict"; + + var controllerId = "upload"; + + class Upload { + + static $inject = ["$upload"]; + constructor( + private $upload: ng.angularFileUpload.IUploadService + ) { + } + + onFileSelect($files: File[]) { + //$files: an array of files selected, each file has name, size, and type. + var uploads: ng.IPromise[] = []; + for (var i = 0; i < $files.length; i++) { + var file = $files[i]; + uploads.push(this.$upload.upload({ + url: "/api/upload", + method: "POST", + data: { + extraData: { + fileName: file.name, test: "anything" + } + }, + file: file + }) + .progress((evt: any) => { + console.log('progress'); + }) + .then(success => { + // file is uploaded successfully + console.log(success.data); + }) + .catch(err => { + console.error(err); + })); + } + } + } + + angular.module("app").controller(controllerId, Upload); +} diff --git a/angular-file-upload/angular-file-upload.d.ts b/angular-file-upload/angular-file-upload.d.ts new file mode 100644 index 000000000..9c3542888 --- /dev/null +++ b/angular-file-upload/angular-file-upload.d.ts @@ -0,0 +1,26 @@ +// Type definitions for Angular File Upload 1.6.7 +// Project: https://github.com/danialfarid/angular-file-upload +// Definitions by: John Reilly +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ng.angularFileUpload { + + interface IUploadService { + + http(config: IFileUploadConfig): IUploadPromise; + upload(config: IFileUploadConfig): IUploadPromise; + } + + interface IUploadPromise extends IHttpPromise { + + progress(callback: IHttpPromiseCallback): IUploadPromise; + } + + interface IFileUploadConfig extends ng.IRequestConfig { + + file: File; + fileName?: string; + } +} \ No newline at end of file diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 4b8da8449..135ac75ad 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Translate (pascalprecht.translate module) +// Type definitions for Angular Translate v2.4.0 (pascalprecht.translate module) // Project: https://github.com/PascalPrecht/angular-translate // Definitions by: Michel Salib // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -42,7 +42,7 @@ declare module ng.translate { instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; - preferredLanguage(): string; + preferredLanguage(langKey?: string): string; proposedLanguage(): string; refresh(langKey?: string): ng.IPromise; storage(): IStorage; @@ -50,6 +50,8 @@ declare module ng.translate { use(): string; use(key: string): ng.IPromise; useFallbackLanguage(langKey?: string): void; + versionInfo(): string; + loaderCache(): any; } interface ITranslateProvider extends ng.IServiceProvider { @@ -61,14 +63,14 @@ declare module ng.translate { useMessageFormatInterpolation(): ITranslateProvider; useInterpolation(factory: string): ITranslateProvider; useSanitizeValueStrategy(value: string): ITranslateProvider; - preferredLanguage(): string; + preferredLanguage(): ITranslateProvider; preferredLanguage(language: string): ITranslateProvider; translationNotFoundIndicator(indicator: string): ITranslateProvider; translationNotFoundIndicatorLeft(): string; translationNotFoundIndicatorLeft(indicator: string): ITranslateProvider; translationNotFoundIndicatorRight(): string; translationNotFoundIndicatorRight(indicator: string): ITranslateProvider; - fallbackLanguage(): string; + fallbackLanguage(): ITranslateProvider; fallbackLanguage(language: string): ITranslateProvider; fallbackLanguage(languages: string[]): ITranslateProvider; use(): string; @@ -89,5 +91,6 @@ declare module ng.translate { determinePreferredLanguage(fn?: () => void): ITranslateProvider; registerAvailableLanguageKeys(): string[]; registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider; + useLoaderCache(cache?: any): ITranslateProvider; } } diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index ba6d0aac9..a71299e25 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -75,7 +75,7 @@ declare module ng.route { * - key - {string}: a name of a dependency to be injected into the controller. * - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead. */ - resolve?: any; + resolve?: {[key: string]: any}; /** * {(string|function())=} * Value to update $location path with and trigger route redirection. diff --git a/any-db-transaction/any-db-transaction-tests.ts b/any-db-transaction/any-db-transaction-tests.ts new file mode 100644 index 000000000..55ca53bdc --- /dev/null +++ b/any-db-transaction/any-db-transaction-tests.ts @@ -0,0 +1,29 @@ + +/// +/// + +"use strict"; + +import anyDB = require("any-db"); +import begin = require("any-db-transaction"); + +var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); + + +var transaction = begin(conn); +var transaction2 = begin(transaction); + +begin(conn, { autoRollback: true }); +begin(conn, (error: Error, result: begin.Transaction): void => { +}); + +transaction.query("SELECT * FROM MyTable"); + +transaction.commit(); +transaction.commit((error: Error): void => { +}); + +transaction.rollback(); +transaction.rollback((error: Error): void => { +}); + diff --git a/any-db-transaction/any-db-transaction.d.ts b/any-db-transaction/any-db-transaction.d.ts new file mode 100644 index 000000000..ca5bc84b0 --- /dev/null +++ b/any-db-transaction/any-db-transaction.d.ts @@ -0,0 +1,94 @@ +// Type definitions for any-db-transaction 2.2.1 +// Project: https://github.com/grncdr/node-any-db-transaction +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "any-db-transaction" { + import anyDB = require("any-db"); + + module begin { + /** + * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, + * but guarantee that all queries take place within a single database transaction or not at all. Note that + * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you + * can simply pass a pool to it: var tx = begin(pool) + * + * By default, any queries that error during a transaction will cause an automatic rollback. If a query has + * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. + * This enables handling errors for an entire transaction in a single place. + * + * Transactions may also be nested by passing a Transaction to begin and these nested transactions can + * safely error and rollback without rolling back their parent transaction + * + * Transaction events: + * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. + * 'commit:start' - Emitted when .commit() is called. + * 'commit:complete' - Emitted after the transaction has committed. + * 'rollback:start' - Emitted when .rollback() is called. + * 'rollback:complete' - Emitted after the transaction has rolled back. + * 'close' - Emitted after rollback or commit completes. + * 'error', err - Emitted under three conditions: + * There was an error acquiring a connection. + * Any query performed in this transaction emits an error that would otherwise go unhandled. + * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. + * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. + */ + interface Transaction extends anyDB.Queryable { + + /** + * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. + * If a continuation is provided it will be called (possibly with an error) after the COMMIT + * statement completes. The transaction object itself will be unusable after calling commit(). + */ + commit(callback?: (error: Error) => void): void; + + /** + * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. + */ + rollback(callback?: (error: Error) => void): void; + } + + interface TransactionOptions { + /** + * Adapter name e.g. 'mysql' + */ + adapter?: anyDB.Adapter; + /** + * SQL statement for beginning a transaction, default 'BEGIN' + */ + begin?: string; + /** + * SQL statement for committing a transaction, default 'COMMIT' + */ + commit?: string; + /** + * SQL statement for rolling back a transaction, default 'ROLLBACK' + */ + rollback?: string; + /** + * Callback for transaction + */ + callback?: (error: Error, transaction: Transaction) => void; + /** + * Rollback automatically on error, default true + */ + autoRollback?: boolean; + } + } + + /** + * Start a transaction + */ + function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + + export = begin; +} + + + diff --git a/any-db/any-db-tests.ts b/any-db/any-db-tests.ts new file mode 100644 index 000000000..15dc6c7e6 --- /dev/null +++ b/any-db/any-db-tests.ts @@ -0,0 +1,38 @@ + +/// + +"use strict"; + +import anyDB = require("any-db"); + +var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb"); +var sql: string = "SELECT * FROM questions"; + +conn.query(sql, [1, "boo"]); + +conn.query(sql).on("data", (row: Object[]): void => { +// nothing +}); + +conn.query(sql, [1, "s"], (error: Error, result: anyDB.ResultSet): void => { + result.rows.length; + result.fields.length; +}); + +conn.end(); + + +var poolConfig: anyDB.PoolConfig = { + min: 1, + max: 200 +}; + +var pool: anyDB.ConnectionPool = anyDB.createPool("mysql://user:password@localhost/testdb", poolConfig); + +pool.query(sql).on("data", (row: Object[]): void => { +// nothing +}); + +pool.close((error: Error): void => { +}); + diff --git a/any-db/any-db.d.ts b/any-db/any-db.d.ts new file mode 100644 index 000000000..04817623a --- /dev/null +++ b/any-db/any-db.d.ts @@ -0,0 +1,303 @@ +// Type definitions for any-db 2.1.0 +// Project: https://github.com/grncdr/node-any-db +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "any-db" { + import events = require("events"); + import stream = require("stream"); + + export interface ConnectOpts { + adapter: string; + } + + export interface Adapter { + name: string; + /** + * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. + * If a continuation is given, it must be called, either with an error or the established connection. + */ + createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; + + /** + * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, + * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract + * by synchronously returning a Query stream + */ + createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; + createQuery(query: Query): Query; + } + /** + * Other properties are driver specific + */ + export interface Field { + name: string; + } + + /** + * ResultSet objects are just plain data that collect results of a query when a continuation + * is provided to Queryable.query. The lastInsertId is optional, and currently supported by + * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. + */ + export interface ResultSet { + /** + * Affected rows. Note e.g. for INSERT queries the rows property is not filled even + * though rowCount is non-zero. + */ + rowCount: number; + /** + * Result rows + */ + rows: Object[]; + /** + * Result field descriptions + */ + fields: Field[]; + + /** + * Not supported by all drivers. + */ + fieldCount?: number; + /** + * Not supported by all drivers. + */ + lastInsertId?: any; + /** + * Not supported by all drivers. + */ + affectedRows?: number; + /** + * Not supported by all drivers. + */ + changedRows?: number; + } + + /** + * Query objects are returned by the Queryable.query method, available on connections, + * pools, and transactions. Queries are instances of Readable, and as such can be piped + * through transforms and support backpressure for more efficient memory-usage on very + * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) + * + * Internally, Query instances are created by a database Adapter and may have more methods, + * properties, and events than are described here. Consult the documentation for your + * specific adapter to find out about any extensions. + * + * Events: + * + * Error event + * The 'error' event is emitted at most once per query. Note that this event will be + * emitted for errors even if a callback was provided, the callback will + * simply be subscribed to the 'error' event. + * One argument is passed to event listeners: + * error - the error object. + * + * Fields event + * A 'fields' event is emmitted before any 'data' events. + * One argument is passed to event listeners: + * fields - an array of [Field][ResultSet] objects. + * + * The following events are part of the stream.Readable interface which is implemented by Query: + * + * Data event + * A 'data' event is emitted for each row in the query result set. + * One argument is passed to event listeners: + * row contains the contents of a single row in the query result + * + * Close event + * A 'close' event is emitted when the query completes. + * No arguments are passed to event listeners. + * + * End event + * An 'end' event is emitted after all query results have been consumed. + * No arguments are passed to event listeners. + */ + export interface Query extends stream.Readable { + /** + * The SQL query as a string. If you are using MySQL this will contain + * interpolated values after the query has been enqueued by a connection. + */ + text: string; + + /** + * The array of parameter values. + */ + values: any[]; + + /** + * The callback (if any) that was provided to Queryable.query. Note that + * Query objects must not use a closed over reference to their callback, + * as other any-db libraries may rely on modifying the callback property + * of a Query they did not create. + */ + callback: (error: Error, results: ResultSet) => void; + } + + /** + * Events: + * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: + * - query: a Query object + */ + export interface Queryable extends events.EventEmitter { + /** + * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. + */ + adapter: Adapter; + + /** + * Execute a SQL statement using bound parameters (if they are provided) and return a Query object + * that is a Readable stream of the resulting rows. If a Continuation is provided the rows + * returned by the database will be aggregated into a [ResultSet][] which will be passed to the + * continuation after the query has completed. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query + + /** + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + // query(query: Query): Query; + } + + /** + * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, + * both of which delegate to the createConnection implementation of the specified adapter. + * While all Connection objects implement the Queryable interface, the implementations in + * each adapter may add additional methods or emit additional events. If you need to access a + * feature of your database that is not described here (such as Postgres' server-side prepared + * statements), consult the documentation for your adapter. + * + * Events: + * Error event + * The 'error' event is emitted when there is a connection-level error. + * No arguments are passed to event listeners. + * + * Open event + * The 'open' event is emitted when the connection has been established and is ready to query. + * No arguments are passed to event listeners. + * + * Close event + * The 'close' event is emitted when the connection has been closed. + * No arguments are passed to event listeners. + */ + export interface Connection extends Queryable { + /** + * Close the database connection. If a continuation is provided it + * will be called after the connection has closed. + */ + end(callback?: (error: Error) => void): void; + } + + export interface ConnectionStatic { + new(): Connection; + + name: string; + createConnection(): void; + createPool(): void; + } + + /** + * ConnectionPool events + * 'acquire' - emitted whenever pool.acquire is called + * 'release' - emitted whenever pool.release is called + * 'query', query - emitted immediately after .query is called on a + * connection via pool.query. The argument is a Query object. + * 'close' - emitted when the connection pool has closed all of it + * connections after a call to close(). + */ + export interface ConnectionPool extends Queryable { + /** + * Implements Queryable.query by automatically acquiring a connection + * and releasing it when the query completes. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; + + /** + * Remove a connection from the pool. If you use this method you must + * return the connection back to the pool using ConnectionPool.release + */ + acquire(callback: (error: Error, result: Connection) => void): void; + + /** + * Return a connection to the pool. This should only be called with connections + * you've manually acquired. You must not continue to use the connection after releasing it. + */ + release(connection: Connection): void; + + /** + * Stop giving out new connections, and close all existing database connections as they + * are returned to the pool. + */ + close(callback?: (error: Error) => void): void; + } + + /** + * A PoolConfig is generally a plain object with any of the following properties (they are all optional): + */ + export interface PoolConfig { + /** + * min (default 0) The minimum number of connections to keep open in the pool. + */ + min?: number; + /** + * max (default 10) The maximum number of connections to keep open in the pool. + * When this limit is reached further requests for connections will queue waiting + * for an existing connection to be released back into the pool. + */ + max?: number; + /** + * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped + */ + idleTimeout?: number; + /** + * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. + */ + reapInterval?: number; + /** + * (default true) When this is true, the pool will reap connections that + * have been idle for more than idleTimeout milliseconds. + */ + refreshIdle?: boolean; + /** + * Called immediately after a connection is first established. Use this to do one-time setup of new connections. + * The supplied Connection will not be added to the pool until you pass it to the done continuation. + */ + onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; + /** + * Called each time a connection is returned to the pool. Use this to restore a connection to + * it's original state (e.g. rollback transactions, set the database session vars). If reset + * fails to call the done continuation the connection will be lost in limbo. + */ + reset?: (connection: Connection, done: (error: Error) => void) => void; + /** + * (default function (err) { return true }) - Called when an error is encountered + * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) + * is truthy the connection will be destroyed, otherwise it will be reset. + */ + shouldDestroyConnection?: (error: Error) => boolean; + } + + /** + * Create a database connection. + * @param url String of the form adapter://user:password@host/database + * @param callback + * @returns Connection object. + */ + export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; + + /** + * Create a database connection. + * @param opts Object with adapter name and any properties that the given adapter requires + * @param callback + * @returns Connection object. + */ + export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; + + + export function createPool(url: string, config: PoolConfig): ConnectionPool; + export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; + +} diff --git a/bcrypt/bcrypt-tests.ts b/bcrypt/bcrypt-tests.ts new file mode 100644 index 000000000..b88d4fb7a --- /dev/null +++ b/bcrypt/bcrypt-tests.ts @@ -0,0 +1,34 @@ +/// + +import bcrypt = require("bcrypt"); + +var num: number; +var str: string; +var bool: boolean; + +str = bcrypt.genSaltSync(); +str = bcrypt.genSaltSync(num); + +bcrypt.genSalt(function (err: Error, salt: string): void { + str = salt; +}); +bcrypt.genSalt(num, function (err: Error, salt: string): void { + str = salt; +}); + +str = bcrypt.hashSync(str, str); +str = bcrypt.hashSync(str, num); + +bcrypt.hash(str, str, function (err: Error, encrypted: string):void { + str = encrypted; +}) +bcrypt.hash(str, num, function (err: Error, encrypted: string): void { + str = encrypted; +}); + +bool = bcrypt.compareSync(str, str); +bcrypt.compare(str, str, function (err: Error, same: boolean): void { + bool = same; +}); + +num = bcrypt.getRounds(str); \ No newline at end of file diff --git a/bcrypt/bcrypt.d.ts b/bcrypt/bcrypt.d.ts new file mode 100644 index 000000000..98d68b773 --- /dev/null +++ b/bcrypt/bcrypt.d.ts @@ -0,0 +1,65 @@ +// Type definitions for bcrypt +// Project: https://www.npmjs.org/package/bcrypt +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "bcrypt" { + /** + * @param rounds The cost of processing the data. Default 10. + */ + export function genSaltSync(rounds?: number): string; + + /** + * @param rounds The cost of processing the data. Default 10. + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ + export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; + /** + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ + export function genSalt(callback: (err: Error, salt: string) => void): void; + + /** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + */ + export function hashSync(data: any, salt: string): string; + /** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + */ + export function hashSync(data: any, rounds: number): string; + + /** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ + export function hash(data: any, salt: string, callback: (err: Error, encrypted: string) => void): void; + /** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ + export function hash(data: any, rounds: number, callback: (err: Error, encrypted: string) => void): void; + + /** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + */ + export function compareSync(data: any, encrypted: string): boolean; + + /** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + * @param callback A callback to be fire once the data has been compared. Uses eio making it asynchronous. + */ + export function compare(data: any, encrypted: string, callback: (err: Error, same: boolean) => void): void; + + /** + * Return the number of rounds used to encrypt a given hash + * + * @param encrypted Hash from which the number of rounds used should be extracted. + */ + export function getRounds(encrypted: string): number; +} diff --git a/bigint/bigint-tests.ts b/bigint/bigint-tests.ts index 8ccf2ba4b..14cdd5b12 100644 --- a/bigint/bigint-tests.ts +++ b/bigint/bigint-tests.ts @@ -49,7 +49,7 @@ bi = BigInt.trim(bi, num); BigInt.addInt_(bi, num); BigInt.add_(bi, bi); BigInt.copy_(bi, bi); -num = BigInt.copyInt_(bi, num); +BigInt.copyInt_(bi, num); BigInt.GCD_(bi, bi); b = BigInt.inverseMod_(bi, bi); BigInt.mod_(bi, bi); diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts index b70f20fa4..a2a8ed417 100644 --- a/bigint/bigint.d.ts +++ b/bigint/bigint.d.ts @@ -1,8 +1,11 @@ -// Type definitions for BigInt v5.5.1 +// Type definitions for BigInt v5.5.3 // Project: https://github.com/Evgenus/BigInt // Definitions by: Eugene Chernyshov // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Development repository: https://github.com/Evgenus/bigint-typescript-definitions +// For answers, fixes and cutting edge version please see development repository. + declare module BigInt { export interface BigInt extends Array { } @@ -11,361 +14,632 @@ declare module BigInt { (): number; } + /** + * Sets a random number generator. + * + * @param {IRandom} random function that returns random number. + */ export function setRandom(random: IRandom): void; /** - * bigInt add(x,y) * return (x+y) for bigInts x and y. + * + * @param {BigInt} x The BigInt augend. + * @param {BigInt} y The BigInt addend. + * + * @return {BigInt} A sum as BigInt. */ export function add(x: BigInt, y: BigInt): BigInt; /** - * bigInt addInt(x,n) * return (x+n) where x is a bigInt and n is an integer. + * + * @param {BigInt} x The BigInt augend. + * @param {number} n The number addend. + * + * @return {BigInt} A sum as BigInt. */ export function addInt(x: BigInt, n: number): BigInt; - interface bigInt2str_T { - /** - * string bigInt2str(x,base) - * return a string form of bigInt x in a given base, with 2 <= base <= 95 - */ - (x: BigInt, base: T): string; - } - - interface bigInt2strSignature extends bigInt2str_T, bigInt2str_T{ - } - - export var bigInt2str: bigInt2strSignature; + /** + * return a string form of bigInt x in a given base, with 2 <= base <= 95. + * + * @param {BigInt} x The BigInt to stringify. + * @param {number} base The base as radix number. + * + * @return {string} A string representation of given BigInt. + */ + export function bigInt2str(x: BigInt, base: number): string; /** - * int bitSize(x) - * return how many bits long the bigInt x is, not counting leading zeros + * return a string form of bigInt x in a given base, with 2 <= base <= 95. + * + * @param {BigInt} x The BigInt to stringify. + * @param {string} base The base as vocabulary of characters. + * + * @return {string} A string representation of given BigInt. + */ + export function bigInt2str(x: BigInt, base: string): string; + + /** + * return how many bits long the bigInt x is, not counting leading zeros. + * + * @param {BigInt} x The BigInt to process. + * + * @return {number} A size in BigInt as number. */ export function bitSize(x: BigInt): number; /** - * bigInt dup(x) - * return a copy of bigInt x + * return a copy of bigInt x. + * + * @param {BigInt} x Source BigInt to be copied. + * + * @return {BigInt} A copy of this object. */ export function dup(x: BigInt): BigInt; /** - * boolean equals(x,y) * is the bigInt x equal to the bigint y? + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * + * @return {boolean} true if the objects are considered equal, false if they are not. */ export function equals(x: BigInt, y: BigInt): boolean; /** - * boolean equalsInt(x,y) * is bigint x equal to integer y? + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * + * @return {boolean} true if the objects are considered equal, false if not. */ export function equalsInt(x: BigInt, y: number): boolean; /** - * bigInt expand(x,n) - * return a copy of x with at least n elements, adding leading zeros if needed + * return a copy of x with at least n elements, adding leading zeros if needed. + * + * @param {BigInt} value The source object to copy. + * @param {number} n The minimal number of elements. + * + * @return {BigInt} A copy of given BigInt. */ export function expand(value: BigInt, n: number): BigInt; /** - * Array findPrimes(n) - * return array of all primes less than integer n + * return array of all primes less than integer n. + * + * @param {number} n Upper limit of search. + * + * @return {Array} The found primes as Array. */ export function findPrimes(n: number): number[]; /** - * bigInt GCD(x,y) * return greatest common divisor of bigInts x and y (each with same number of elements). + * + * @param {BigInt} x The BigInt to process. + * @param {BigInt} y The BigInt to process. + * + * @return {BigInt} A greatest common divisor as BigInt. */ export function GCD(x: BigInt, y: BigInt): BigInt; /** - * boolean greater(x,y) * is x>y? (x and y are nonnegative bigInts) + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * + * @return {boolean} true if x is greater, false if it's not. */ export function greater(x: BigInt, y: BigInt): boolean; /** - * boolean greaterShift(x,y,shift) * is (x <<(shift*bpe)) > y? + * + * @param {BigInt} x BigInt to be compared. + * @param {BigInt} y BigInt to be compared. + * @param {number} shift The shift amount in bits. + * + * @return {boolean} true if x is greater, false if it's not. */ export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean; /** - * bigInt int2bigInt(t,n,m) - * return a bigInt equal to integer t, with at least n bits and m array elements + * return a bigInt equal to integer t, with at least n bits and m array elements. + * + * @param {number} t The number to process. + * @param {number=} n (Optional) the number to process. + * @param {number=} m (Optional) the number to process. + * + * @return {BigInt} A BigInt equivalent of given number. */ export function int2bigInt(t: number, n?: number, m?: number): BigInt; /** - * bigInt inverseMod(x,n) - * return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null + * return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null. + * + * @param {BigInt} x The BigInt base. + * @param {BigInt} n The BigInt divisor. + * + * @return {BigInt} A BigInt remainder. */ export function inverseMod(x: BigInt, n: BigInt): BigInt; /** - * int inverseModInt(x,n) - * return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse + * return x**(-1) mod n, for integers x and n. + * Return 0 if there is no inverse. + * + * @param {number} x The BigInt base. + * @param {number} n The BigInt divisor. + * + * @return {BigInt} A BigInt remainder. */ export function inverseModInt(x: number, n: number): BigInt; /** - * boolean isZero(x) * is the bigInt x equal to zero? + * + * @param {BigInt} x BigInt to be compared. + * + * @return {boolean} true if zero, false if not. */ export function isZero(x: BigInt): boolean; /** - * boolean millerRabin(x,b) - * does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1=1). If s=1, then the most significant of those n bits is set to 1. + * return an n-bit random BigInt (n>=1). + * If s=1, then the most significant of those n bits is set to 1. + * + * @param {number} n The number of bits (n>=1). + * @param {number} s The sign bit. + * + * @return {BigInt} A new random BigInt. */ export function randBigInt(n: number, s: number): BigInt; /** - * bigInt randTruePrime(k) * return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + * + * @param {number} k The number of bits. + * + * @return {BigInt} A new random BigInt. */ export function randTruePrime(k: number): BigInt; /** - * bigInt randProbPrime(k) - * return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80). + * return a new, random, k-bit, probable prime bigInt. + * Probability it's composite less than 2^- 80. + * + * @param {number} k The number of bits. + * + * @return {BigInt} A new probably random BigInt. */ export function randProbPrime(k: number): BigInt; - interface str2bigInt_T { - /** - * bigInt str2bigInt(s,b,n,m) - * return a bigInt for number represented in string s in base b with at least n bits and m array elements - */ - (s: string, b: T, n?: number, m?: number): BigInt; - } - - interface str2bigIntSignature extends str2bigInt_T, str2bigInt_T { - } - - export var str2bigInt: str2bigIntSignature; + /** + * return a bigInt for number represented in string s in base b with at least n bits and m array + * elements. + * + * @param {string} s The string representation of number. + * @param {number} b The base as radix number. + * @param {number=} n (Optional) minimal bit length as number. + * @param {number=} m (Optional) the number of array elements as number. + * + * @return {BigInt} A parsed BigInt. + */ + export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt; /** - * bigInt sub(x,y) - * return (x-y) for bigInts x and y. Negative answers will be 2s complement + * return a bigInt for number represented in string s in base b with at least n bits and m array + * elements. + * + * @param {string} s The string representation of number. + * @param {string} b The base as string vocabulary of characters. + * @param {number=} n (Optional) minimal bit length as number. + * @param {number=} m (Optional) the number of array elements as number. + * + * @return {BigInt} A parsed BigInt. + */ + export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt; + + /** + * return (x-y) for bigInts x and y. + * Negative answers will be 2s complement. + * + * @param {BigInt} x The minuend as BigInt. + * @param {BigInt} y The subtrahend as BigInt. + * + * @return {BigInt} A difference BigInt. */ export function sub(x: BigInt, y: BigInt): BigInt; /** - * bigInt trim(x,k) - * return a copy of x with exactly k leading zero elements + * return a copy of x with exactly k leading zero elements. + * + * @param {BigInt} x The BigInt to be copied. + * @param {number} k The number of zeroes. + * + * @return {BigInt} A copy BigInt. */ export function trim(x: BigInt, k: number): BigInt; /** - * void addInt_(x,n) - * do x=x+n where x is a bigInt and n is an integer + * do x=x+n where x is a bigInt and n is an integer. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt accumulator. + * @param {number} n The number addend. */ export function addInt_(x: BigInt, n: number): void; /** - * void add_(x,y) - * do x=x+y for bigInts x and y + * do x=x+y for bigInts x and y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt accumulator. + * @param {BigInt} y The BigInt addend. */ export function add_(x: BigInt, y: BigInt): void; /** - * void copy_(x,y) - * do x=y on bigInts x and y + * do x=y on bigInts x and y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt destination. + * @param {BigInt} y The BigInt source. */ export function copy_(x: BigInt, y: BigInt): void; /** - * void copyInt_(x,n) - * do x=n on bigInt x and integer n + * do x=n on bigInt x and integer n. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt destination. + * @param {number} n The number source. */ - export function copyInt_(x: BigInt, n: number): number; + export function copyInt_(x: BigInt, n: number): void; /** - * void GCD_(x,y) - * set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + * set x to the greatest common divisor of bigInts x and y, (y is destroyed). + * This never overflows its array. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt first dividend. + * @param {BigInt} y The BigInt second dividend. */ export function GCD_(x: BigInt, y: BigInt): void; /** - * boolean inverseMod_(x,n) - * do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist + * do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt base and the remainder result. + * @param {BigInt} n The BigInt divisor. + * + * @return {boolean} true if inverse does exist, false if doesn't. */ export function inverseMod_(x: BigInt, n: BigInt): boolean; /** - * void mod_(x,n) * do x=x mod n for bigInts x and n. (This never overflows its array). + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt dividend and the remainder result. + * @param {BigInt} n The BigInt divisor. */ export function mod_(x: BigInt, n: BigInt): void; /** - * void mult_(x,y) * do x=x*y for bigInts x and y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt multiplicand and the product result. + * @param {BigInt} y The BigInt multiplier. */ export function mult_(x: BigInt, y: BigInt): void; /** - * void multMod_(x,y,n) - * do x=x*y mod n for bigInts x,y,n. + * do x=x*y mod n for bigInts x,y,n. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt multiplicand and the remainder result. + * @param {BigInt} y The BigInt multiplier. + * @param {BigInt} n The BigInt divisor. */ export function multMod_(x: BigInt, y: BigInt, n: BigInt): void; /** - * void powMod_(x,y,n) - * do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1. + * do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. + * 0**0=1. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt base and the remainder result. + * @param {BigInt} y The BigInt exponent. + * @param {BigInt} n The BigInt divisor. */ export function powMod_(x: BigInt, y: BigInt, n: BigInt): void; /** - * void randBigInt_(b,n,s) - * do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1. + * do b = an n-bit random BigInt. + * if s=1, then nth bit (most significant bit) is set to 1. n>=1. + * + * @private Intend to be internal function. + * + * @param {BigInt} b The BigInt destination. + * @param {number} n The number of bits. + * @param {number} s The sign bit number. */ export function randBigInt_(b: BigInt, n: number, s: number): void; /** - * void randTruePrime_(ans,k) * do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb. + * + * @private Intend to be internal function. + * + * @param {BigInt} ans The destination. + * @param {number} k The number of bits. */ export function randTruePrime_(ans: BigInt, k: number): void; /** - * void sub_(x,y) * do x=x-y for bigInts x and y. Negative answers will be 2s complement. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt minuend and the result difference. + * @param {BigInt} y The BigInt subtrahend . */ export function sub_(x: BigInt, y: BigInt): void; /** - * void addShift_(x,y,ys) * do x=x+(y<<(ys*bpe)) + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt accumulator. + * @param {BigInt} y The BigInt addend to be shifted. + * @param {number} ys The number of shift amount. */ export function addShift_(x: BigInt, y: BigInt, ys: number): void; /** - * void carry_(x) * do carries and borrows so each element of the bigInt x fits in bpe bits. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt to process. */ export function carry_(x: BigInt): void; /** - * void divide_(x,y,q,r) - * divide x by y giving quotient q and remainder r + * divide x by y giving quotient q and remainder r. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt dividend. + * @param {BigInt} y The BigInt divisor. + * @param {BigInt} q The BigInt quotient. + * @param {BigInt} r The BigInt remainder. */ export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void; /** - * int divInt_(x,n) - * do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array). + * do x=floor(x/n) for bigInt x and integer n, and return the remainder. + * This never overflows its array. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt dividend and the quotient result. + * @param {number} n The number divisor. + * + * @return {number} A number remainder. */ export function divInt_(x: BigInt, n: number): number; /** - * void eGCD_(x,y,d,a,b) - * sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y + * sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt to process. + * @param {BigInt} y The BigInt to process. + * @param {BigInt} d The BigInt to process. + * @param {BigInt} a The BigInt to process. + * @param {BigInt} b The BigInt to process. */ export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void; /** - * void halve_(x) - * do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array). + * do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. + * This never overflows its array. + * + * @private Intend to be internal function. + * + * @param {BigInt} x The BigInt to process. */ export function halve_(x: BigInt): void; /** - * void leftShift_(x,n) * left shift bigInt x by n bits. n + +module CanvasJS.Tests { + // Column Chart + var columnChart = new CanvasJS.Chart("chartContainer", + { + title: { + text: "Top Oil Reserves", + }, + axisY: { + title: "Reserves(MMbbl)" + }, + legend: { + verticalAlign: "bottom", + horizontalAlign: "center" + }, + theme: "theme2", + data: [ + { + type: "column", + showInLegend: true, + legendMarkerColor: "grey", + legendText: "MMbbl = one million barrels", + dataPoints: [ + { y: 297571, label: "Venezuela" }, + { y: 267017, label: "Saudi" }, + { y: 175200, label: "Canada" }, + { y: 154580, label: "Iran" }, + { y: 116000, label: "Russia" }, + { y: 97800, label: "UAE" }, + { y: 20682, label: "US" }, + { y: 20350, label: "China" } + ] + } + ] + }); + columnChart.render(); + + // Line Chart + var lineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Earthquakes - per month" + }, + axisX: { + valueFormatString: "MMM", + interval: 1, + intervalType: "month" + + }, + axisY: { + includeZero: false + + }, + data: [ + { + type: "line", + //lineThickness: 3, + dataPoints: [ + { x: new Date(2012, 0, 1), y: 450 }, + { x: new Date(2012, 1, 1), y: 414 }, + { x: new Date(2012, 2, 1), y: 520, indexLabel: "highest", markerColor: "red", markerType: "triangle" }, + { x: new Date(2012, 3, 1), y: 460 }, + { x: new Date(2012, 4, 1), y: 450 }, + { x: new Date(2012, 5, 1), y: 500 }, + { x: new Date(2012, 6, 1), y: 480 }, + { x: new Date(2012, 7, 1), y: 480 }, + { x: new Date(2012, 8, 1), y: 410, indexLabel: "lowest", markerColor: "DarkSlateGrey", markerType: "cross" }, + { x: new Date(2012, 9, 1), y: 500 }, + { x: new Date(2012, 10, 1), y: 480 }, + { x: new Date(2012, 11, 1), y: 510 } + + ] + } + + + ] + }); + lineChart.render(); + + // Spline Chart + var splineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Game of Thrones, Viewers of the first airing on HBO" + }, + axisY: { + includeZero: false, + // suffix: " k", + valueFormatString: "#,,.", + suffix: " mn" + }, + toolTip: { + shared: true + }, + data: [ + { + type: "spline", + showInLegend: true, + name: "Season 2", + // markerSize: 0, + // color: "rgba(54,158,173,.6)", + dataPoints: [ + { label: "Ep. 1", y: 3858000 }, + { label: "Ep. 2", y: 3759000 }, + { label: "Ep. 3", y: 3766000 }, + { label: "Ep. 4", y: 3654000 }, + { label: "Ep. 5", y: 3903000 }, + { label: "Ep. 6", y: 3879000 }, + { label: "Ep. 7", y: 3694000 }, + { label: "Ep. 8", y: 3864000 }, + { label: "Ep. 9", y: 3384000 }, + { label: "Ep. 10", y: 4200000 } + + ] + }, + { + type: "spline", + showInLegend: true, + // markerSize: 0, + name: "Season 1", + dataPoints: [ + { label: "Ep. 1", y: 2220000 }, + { label: "Ep. 2", y: 2200000 }, + { label: "Ep. 3", y: 2440000 }, + { label: "Ep. 4", y: 2450000 }, + { label: "Ep. 5", y: 2580000 }, + { label: "Ep. 6", y: 2440000 }, + { label: "Ep. 7", y: 2400000 }, + { label: "Ep. 8", y: 2720000 }, + { label: "Ep. 9", y: 2660000 }, + { label: "Ep. 10", y: 3040000 } + + ] + } + ], + legend: { + cursor: "pointer", + itemclick: function (e) { + if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { + e.dataSeries.visible = false; + } + else { + e.dataSeries.visible = true; + } + splineChart.render(); + } + + }, + }); + splineChart.render(); + + // Bar Chart + var barChart = new CanvasJS.Chart("chartContainer", { + + title: { + text: "Fortune Global 500 Companies by Country" + }, + axisX: { + interval: 1, + gridThickness: 0, + labelFontSize: 10, + labelFontStyle: "normal", + labelFontWeight: "normal", + labelFontFamily: "Lucida Sans Unicode" + }, + axisY: { + interlacedColor: "rgba(1,77,101,.2)", + gridColor: "rgba(1,77,101,.1)" + }, + data: [ + { + type: "bar", + name: "companies", + axisYType: "secondary", + color: "#014D65", + dataPoints: [ + { y: 5, label: "Sweden" }, + { y: 6, label: "Taiwan" }, + { y: 7, label: "Russia" }, + { y: 8, label: "Spain" }, + { y: 8, label: "Brazil" }, + { y: 8, label: "India" }, + { y: 9, label: "Italy" }, + { y: 9, label: "Australia" }, + { y: 12, label: "Canada" }, + { y: 13, label: "South Korea" }, + { y: 13, label: "Netherlands" }, + { y: 15, label: "Switzerland" }, + { y: 28, label: "Britain" }, + { y: 32, label: "Germany" }, + { y: 32, label: "France" }, + { y: 68, label: "Japan" }, + { y: 73, label: "China" }, + { y: 132, label: "US" } + ] + } + ] + }); + barChart.render(); + + // Pie Chart + var pieChart = new CanvasJS.Chart("chartContainer", + { + title: { + text: "Desktop Search Engine Market Share, Dec-2012" + }, + legend: { + verticalAlign: "center", + horizontalAlign: "left", + fontSize: 20, + fontFamily: "Helvetica" + }, + theme: "theme2", + data: [ + { + type: "pie", + indexLabelFontFamily: "Garamond", + indexLabelFontSize: 20, + indexLabel: "{label} {y}%", + startAngle: -20, + showInLegend: true, + toolTipContent: "{legendText} {y}%", + dataPoints: [ + { y: 83.24, legendText: "Google", label: "Google" }, + { y: 8.16, legendText: "Yahoo!", label: "Yahoo!" }, + { y: 4.67, legendText: "Bing", label: "Bing" }, + { y: 1.67, legendText: "Baidu", label: "Baidu" }, + { y: 0.98, legendText: "Others", label: "Others" } + ] + } + ] + }); + pieChart.render(); + + addColorSet("MyColorSet", [ + "123456", + "blue", + "red", + "orange" + ]); + + addCultureInfo("js", { + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] + }); +} \ No newline at end of file diff --git a/canvasjs/canvasjs.d.ts b/canvasjs/canvasjs.d.ts new file mode 100644 index 000000000..f572ce329 --- /dev/null +++ b/canvasjs/canvasjs.d.ts @@ -0,0 +1,959 @@ +// Type definitions for CanvasJS v1.5.1 GA +// Project: http://canvasjs.com/ +// Definitions by: Mark Overholt +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module CanvasJS { + class Chart { + + /** + * The current options of the chart. + */ + options: ChartOptions; + + /** + * Initializes a new instance of CanvasJS Chart. + * @param containerId the DOM ID of the location where the chart is to be rendered + * @param options the options used to render the chart + */ + constructor(containerId: string, options?: ChartOptions); + + /** + * Renders the chart. + * @param options an optional set of options that will override the constructed values. + */ + render(options?: ChartOptions): void; + } + + /** + * Adds a new chart color set + * @param the name of the color set + * @param an array of colors. + */ + function addColorSet(colorSetName: string, colorSetArray: string[]): void; + + + /** + * Adds a new culture info for your chart + * @param culture the name of the culture + * @param the information used by this culture + */ + function addCultureInfo(culture: string, info: CultureInfo): void; + + interface CultureInfo { + /** + * Character used to separate fractional part from the whole number. + */ + decimalSeparator?: string; + /** + * Also referred to as Thousand Separator + */ + digitGroupSeparator?: string; + /** + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + */ + zoomText?: string; + /** + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + */ + panText?: string; + /** + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + */ + resetText?: string; + /** + * Set text is shown instead of Save as PNG. + */ + savePNGText?: string; + /** + * Set text is shown instead of Save as JPG. + */ + saveJPGText?: string; + /** + * Tool Tip for Menu Button. + */ + menuText?: string; + /** + * Day names starting from Sunday. Should be exactly 7 in total. + */ + days?: string[]; + /** + * Short Day names starting from Sunday. Should be exactly 7 in total. + */ + shortDays?: string[]; + /** + * Month Names starting from January + */ + months?: string[]; + /** + * Short Month Names starting from January + */ + shortMonths?: string[]; + } + + interface ChartOptions { + /** + * Enables / Disables Chart interactivity like toolTip, mouse and touch events + * Default: true + * Example: false, true + */ + interactivityEnabled?: boolean; + /** + * Enables Animation while rendering the Chart. + * Default: true + * Example: false, true + */ + animationEnabled?: boolean; + /** + * While exporting any chart, “Chart” is used as the default fine name with corresponding extension “jpg” or “png”. You can override this name using exportFileName property. + * Default: Chart + */ + exportFileName?: string; + /** + * Setting exportEnabled to true enables the export feature. As of now JPG & PNG formats are supported. Export feature is available in all Chart Types. + * Default: false + * Options: true, false + */ + exportEnabled?: boolean; + /** + * Setting zoomEnabled to true enables zooming and panning feature of Chart. This way you can zoom into an area of interest when there is a large amount of data. This will also allow you to pan through the chart. If not set, the property is automatically enabled for large number of dataPoints. You can switch between zooming & panning using the toolbar that appears on the chart. After Zooming in, you can reset the chart by clicking the reset button. + * Default: false + * Options: true, false + */ + zoomEnabled?: boolean; + /** + * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. + * Default: “theme1″ + * Options: “theme1″,”theme2″, “theme3″ + */ + theme?: string; + /** + * Sets the background color of entire Chart Area. Values can be “HTML Color Name”, “hex code” or “rgba values” + * Default: “white” + * Example: “yellow”, “#F5DEB3″.. + */ + backgroundColor?: string; + /** + * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. You can either choose from the pre-defined Color Sets or define your own Color Set. + * Default: “colorset1″ or as defined in the selected theme + * Example: “colorSet1″, “colorSet2″, “colorSet3″ + */ + colorSet?: string; + /** + * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). By default CanvasJS is set to Neutral English Culture – “en”. + * Default: “en” + */ + culture?: string; + /** + * Sets the width of the Chart. + * Default: Takes chart container’s width by default. If the width is not set for the chart container, defaults to 500. + * Example: 380, 500, 720 + */ + width?: number; + /** + * Sets the width of the Chart + * Default: Takes chart container’s height by default. If the height is not set for the chart container, defaults to 400. + * Example: 260, 300, 400 + */ + height?: number; + /** + * Title allows you to set content, appearance and position of Chart’s Title. + */ + title: ChartTitleOptions; + /** + * Whenever the chart contains multiple dataSeries, it is recommended to represent each dataSeries in a legend. This way it becomes easier for the user to know what exactly is represented by each of the dataSeries. In case of Pie and Doughnut charts, an entry is created for each dataPoint and in rest of the chart types entries are created for each dataSeries. + * You can selectively show or hide a dataSeries in the Legend using showInLegend property of dataSeries. + */ + legend?: ChartLegendOptions; + /** + * axisX object lets you set various parameters of X Axis like interval, grid lines, etc. It is mostly horizontal, except when we are working with Bar Charts, where axisX is vertical. + */ + axisX?: ChartAxisXOptions; + /** + * axisY object lets you set various parameters of Y Axis like interval, grid lines, etc. It is mostly vertical, except when we are working with Bar Charts, where axisY is horizontal. + */ + axisY?: ChartAxisYOptions; + /** + * toolTip object lets user set behaviour of toolTip at global level like enabling/disabling animation, setting Border Color, sharing toolTip between multiple dataSeries, etc. You can also disable the toolTip by setting enabled property to false. + */ + toolTip?: ChartToolTipOptions; + /** + * data is an array of dataSeries Objects. + */ + data: ChartDataOptions[]; + } + + interface ChartTitleOptions { + /** + * Sets the Title’s text. + * Default: null + * Example: “Chart title” + */ + text?: string; + /** + * This property lets you align the Chart Title vertically. + * Default: “top” + * Options: “top”, “center”, “bottom” + */ + verticalAlign?: string; + /** + * This property lets you align the Chart Title horizontally. + * Default: “center” + * Options: “left”, “right”, “center” + */ + horizontalAlign?: string; + /** + * Sets the font Size of Chart Title in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16,18,22 .. + */ + fontSize?: number; + /** + * Sets the Font Family of Chart Title. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “arial” , “tahoma”, “verdana” .. + */ + fontFamily?: string; + /** + * Sets the Font Weight used in the Chart Title. + * Default: “bold” + * Options: “lighter”, “normal”, “bold” , “bolder” + */ + fontWeight?: string; + /** + * Sets the font color of Chart Title. The value of fontColor can be a “HTML Color Name” or “hex” code . + * Default: “#3A3A3A” + * Example: “red”, “#FAC003″ .. + */ + fontColor?: string; + /** + * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. + * Default: “normal” + * Options: “normal”, “italic” , “oblique” + */ + fontStyle?: string; + /** + * Sets the thickness of border around the Title in pixels. To display border around title, set the borderThickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ + borderThickness?: number; + /** + * To display rounded borders around the title, set the cornerRadius of title. Higher the value, more rounded are the corners. + * Default: 0 + * Options: 5,8 .. + */ + cornerRadius?: number; + /** + * Sets the color of border around Chart Title. Values of borderColor can be “HTML Color Name” or “hex” code . + * Default: “black” + * Example: “red”, “#FF0000″ .. + */ + borderColor?: string; + /** + * Sets the background color of Chart Title. Values can be “HTML Color Name” or “hex” code. + * Default: null + * Example: “red”, “#FF0000″ .. + */ + backgroundColor?: string; + /** + * This property lets you set margin around the Chart Title in pixels. + * Default: 10 + * Example: 4,12 .. + */ + margin?: number; + /** + * This property allows you to set the padding for Chart Title + * Default: 0 + * Example: 5, 8 .. + */ + padding?: number; + } + + interface ChartLegendOptions { + /** + * Sets the font Size of Legend Text in pixels. + * Default: 12 + * Example: 16,18,22 .. + */ + fontSize?: number; + /** + * Sets the Font Family of Legend Text. + * Default: “calibri” + * Example: “arial” , “tahoma”, “verdana” .. + */ + fontFamily?: string; + /** + * Sets the font color of Legend Text . The value of fontColor can be a “HTML Color Name” or “hex” code . + * Default: “black” + * Example: “red”, “#FAC003″ .. + */ + fontColor?: string; + /** + * Sets the Font Weight of Legend Text. + * Default: “normal” + * Example: “lighter”, “normal”, “bold” , “bolder” + */ + fontWeight?: string; + /** + * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. + * Default: “normal” + * Example: “normal”, “italic” , “oblique” + */ + fontStyle?: string; + /** + * This property lets you align the Legend Position vertically. + * Default: “bottom” + * Example: “top”, “center”, “bottom” + */ + verticalAlign?: string; + /** + * This property lets you align the Legend Position horizontally. + * Default: “right” + * Example: “left”, “right”, “center” + */ + horizontalAlign?: string; + /** + * Sets the mouseover event handler for the legend, which is triggered when the user moves the mouse(input device) over a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmouseover?: (event: ChartEvent) => void; + /** + * Sets the mousemove event handler for the legend, which is triggered when the user moves the mouse(input device) within a legend item. When the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmousemove?: (event: ChartEvent) => void; + /** + * Sets the mouseout event handler for the legend, which is triggered when the user moves the mouse pointer outside a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmouseout?: (event: ChartEvent) => void; + /** + * Sets the click event handler for the legend, which is triggered when the user clicks on a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemclick?: (event: ChartEvent) => void; + } + + interface ChartEvent { + /** + * The x value of the item + */ + x: any; + /** + * The y value of the item + */ + y: number; + /** + * The chart object + */ + chart: Chart; + /** + * The datapoint options + */ + dataPoint: ChartDataPoint; + /** + * The data series options + */ + dataSeries: ChartDataOptions; + /** + * The index of the data point + */ + dataPointIndex: number; + /** + * The index of the data series + */ + dataSeriesIndex: number; + } + + interface ChartAxisXOptions { + /** + * Sets the Axis Title. + * Default: null + * Example: “Axis X Title” + */ + title?: string; + /** + * Sets the Font Color of Axis Title. The value of titleFontColor can be a “HTML Color Name” or “hex” code . + * Default: “#666666″ + * Example: “red”, “#006400″ . + */ + titleFontColor?: string; + /** + * Sets the Font Size of Axis Title in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16, 25 .. + */ + titleFontSize?: number; + /** + * Sets the Font Family of Axis Title. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma, “verdana” .. + */ + titleFontFamily?: string; + /** + * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. + * Default: “normal” + * Options: “lighter”, “normal”, “bold” , “bolder” + */ + titleFontWeight?: string; + /** + * Sets the Font Style of Axis Title. It can be set to one of the below options. + * Default: “normal” + * Options: “normal”, “italic” , “oblique” + */ + titleFontStyle?: string; + /** + * This property lets you set margin between chart’s boundary and Axis. + * Default: 2 + * Example: 8, 10.. + */ + margin?: number; + /** + * Sets the angle for Axis Labels. + * Default: null + * Example: 20, 45, -30 .. + */ + labelAngle?: number; + /** + * Sets the Axis Label color. The value of labelFontColor can be a “HTML Color Name” or “hex” code . + * Default: “grey” + * Example: “red”, “#FAC003″ .. + */ + labelFontColor?: string; + /** + * Sets the Axis Label Font Size in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16, 18, 22.. + */ + labelFontSize?: number; + /** + * Sets the Font Family of Axis labels. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma”, “verdana” .. + */ + labelFontFamily?: string; + /** + * Set the font Weight used in Axis Labels. It can be set to one of the options below. + * Default: “normal” + * Options: “lighter”, “normal”, “bold” , “bolder” + */ + labelFontWeight?: string; + /** + * Sets the Font Style of Axis Labels. It can be set to one of the below options. + * Default: “normal” + * Options: “italic”, “oblique”, “normal” + */ + labelFontStyle?: string; + /** + * A string that prepends all the labels on axisX. + * Default: null + * Example: “$”,”cat”.. + */ + prefix?: string; + /** + * A string that appends all the labels on axisX. + * Default: null + * Example: “$”,”cat”.. + */ + suffix?: string; + /** + * Defines how values must be formatted before they appear on Axis X. You can format numbers and date time values using this property. Below you will find descriptive table explaining various specifiers with example. + */ + valueFormatString?: string; + /** + * Sets the minimum value of Axis. Values smaller than minimum are clipped. + * Default: Automatically Calculated based on the data + * Example: 100, 350.. + */ + minimum?: number; + /** + * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. + * Default: Automatically Calculated based on the data + * Example: 100, 350.. + */ + maximum?: number; + /** + * Sets the distance between Tick Marks, Grid Lines and Interlaced Colors. + * Default: Automatically Calculated + * Example: 50, 75.. + */ + interval?: number; + /** + * intervalType is the unit of interval property. intervalType is by default set to “number” and hence you need to specify the interval type (eg “week”, “month”, etc) depending on the type of interval you intend to set. If required interval is 3 months, you need to provide interval as 3 and intervalType as “month” + * Default: Automatically handled when interval property is not set. Defaults to “number” when you set the interval. + * Option: “number”,”millisecond” ,”second”,” minute”, “hour”, “day”, “month” ,”year” + * Example: for interval as 15 minutes, set interval as 15, and set intervalType as “minute”, + */ + intervalType?: string; + /** + * Sets the length of Tick Marks that are drawn on the Axis. + * Default: 5 + * Example: 10, 14.. + */ + tickLength?: number; + /** + * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a “HTML Color Name” or “hex” code . + * Default: “#BBBBBB” + * Example: “red”, “#006400″. + */ + tickColor?: string; + /** + * Sets the thickness of the Tick Marks in pixels. + * Default: 2 + * Example: 3, 4.. + */ + tickThickness?: number; + /** + * Sets the color of Axis line. Axis line color can be a “HTML Color Name” or “hex” code . + * Default: “#BBBBBB” + * Example: “blue”,”#21AB13″.. + */ + lineColor?: string; + /** + * Sets the Thickness of Axis line in pixels. + * Default: 2 + * Example: 2, 4.. + */ + lineThickness?: string; + /** + * Sets the Interlacing Color that alternates between the set interval. If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a “HTML Color Name” or “hex” code . + * Default: null + * Example: “#F8F1E4″, “#FEFDDF” …. + */ + interlaceColor?: string; + /** + * Sets the Thickness of Grid Lines. To display grid on Axis X, set the Grid Thickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ + gridThickness?: number; + /** + * Sets the Color of Grid Lines. Value of gridColor can be a “HTML Color Name” or “hex” code . + * Default: “#BBBBBB” + * Example: “red”, “#FEFDDF” .. + */ + gridColor?: string; + /** + * Strip Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are sometimes referred to as trend lines. + * If you want to just mark a certain position on the axis, you can set the value attribute and it’ll draw a line at that position with the set thickness. If you want to shade a region instead, you need to set startValue and endValue attributes. This will fill the area within the specified range. + * In the case you set startValue and endValue attributes, value and thickness attributes are ignored (as either a single thread of line can exist, or a shaded region between two given points). + * Strip Lines can be displayed using AxisX or AxisY’s stripLines array. This allows you to have one or more strip lines on both x & y axis. + */ + stripLines?: ChartStripLines; + } + + interface ChartStripLines { + /** + * Sets the point where the stripLine has to be plotted or drawn along the axis X. + * Default: null + * Example: 20,30,100,50 + */ + value?: number; + /** + * Sets the point where the stripLine’s shaded region begins on the x-axis. + * Default: null + * Example: 20,30,100,50 + */ + startValue?: number; + /** + * Sets the point where the stripLine’s shaded region ends on the x-axis. + * Default: null + * Example: 50,60,200,300 + */ + endValue?: number; + /** + * Sets the thickness of the stripLine in pixels. + * Default: 2 + * Example: 2,4,5,6 + */ + thickness?: number; + /** + * Sets the color of the stripLine. + * Default: “orange” + * Example: “green”, “#23EA23″ + */ + color?: string; + /** + * Sets the label of the stripLine. These are shown on top of axis labels. + * Default: “” (empty string) + * Example: “Threshold”, “Deaths in 1920″ + */ + label?: string; + /** + * Sets the background color of stripLine’s label. + * Default: “#eeeeee” + * Example: “red”,”#fabd76″ + */ + labelBackgroundColor?: string; + /** + * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. + * Default: “arial” + * Example: “Arial, Trebuchet MS, Tahoma, sans-serif” + */ + labelFontFamily?: string; + /** + * Sets the font color of label. + * Default: “orange” + * Example: “blue”,”#4135e9″ + */ + labelFontColor?: string; + /** + * Sets the font size of the label in pixels. + * Default: 12 + * Example: 18,19,20,22 + */ + labelFontSize?: number; + /** + * Sets the font weight of stripLine’s label. + * Default: “normal” + * Example: “lighter”,”normal”,”bold”,”bolder” + */ + labelFontWeight?: string; + /** + * Sets the font style of stripLine’s label. + * Default: “normal” + * Example: “normal”,”italic”,”oblique” + */ + labelFontStyle?: string; + } + + interface ChartAxisYOptions extends ChartAxisXOptions { + /** + * When includeZero is set to true, axisY sets the range in such a way that Zero is a part of it. It is set to true by default. But, whenever y values are very big and difference among dataPoints are hard to judge, setting includeZero to false makes axisY to set a range that makes the differences prominently visible. + * Default: true + * Example: true, false + */ + includeZero?: boolean; + } + + interface ChartToolTipOptions { + /** + * Enables or Disables the toolTip for the chart. + * Default: True + * Example: True, False + */ + enabled?: boolean; + /** + * In a Multi-Series or a Combination Chart, it is often required to display all values common to x value in a single bubble. Setting shared to true will show in a common bubble all the values of y from each series next to their name. + * Default: True + * Example: True, False + */ + shared?: boolean; + /** + * toolTip for entire chart can be set by adding content at toolTip object. content can either be a string or a custom function that returns HTML/String to be displayed inside the toolTip. + * Default: auto + */ + content?: string; + /** + * While mouse hovers from one dataPoint to another there is a smooth transition in toolTip. This effect can be controlled by animationEnabled Property. Setting it to false, will disable the animation and toolTip will directly switch from one dataPoint to the other. + * Default: True + * Example: True, False + */ + animationEnabled?: boolean; + /** + * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. + * Default: dataSeries color/ dataPoint color + * Example: “red”, “#808080″.. + */ + borderColor?: string; + } + + interface ChartDataCommon { + /** + * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. + * Default: Automatically Named (“dataPoint 1″, “dataPoint 2″ .. ) + * Example: “apple”, “mango” .. + */ + name?: string; + /** + * Sets the color of dataSeries. The value of tickColor can be a “HTML Color Name” or “Hex Code”. + * Default: Automatically set from Theme. + * Example: “red”, “green” .. + */ + color?: string; + /** + * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. + * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. + * eg: indexLabel: “{x}: {y[#index]}” + * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. + * Default: null + * Example: “{label}”, “Win”, “x: {x}, y: {y} ” + */ + indexLabel?: string; + /** + * Using this property you can define whether to render indexLabel “inside” or “outside” the dataPoint. + * Default: “outside” + * Example: “outside”, “inside” + */ + indexLabelPlacement?: string; + /** + * Sets the Orientation of indexLabel to “horizontal” or “vertical”. + * Default: “horizontal” + * Options: “horizontal”, “vertical” + */ + indexLabelOrientation?: string; + /** + * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a “HTML Color Name” or “Hex Code”. + * Default: null + * Example: “red”, “#FAC003″ .. + */ + indexLabelBackgroundColor?: string; + /** + * Sets the Index Label’s Font Style. It can be set to one of the below options. + * Default: “normal” + * Options: “italic”, “oblique”, “normal” + */ + indexLabelFontStyle?: string; + /** + * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a “HTML Color Name” or “Hex Code”. + * Default: “grey” + * Example: “red”, “#FAC003″ .. + */ + indexLabelFontColor?: string; + /** + * Sets the Index Label’s Font Size in pixels. + * Default: 18 + * Example: 12, 16, 22.. + */ + indexLabelFontSize?: number; + /** + * Sets the Index Label’s Font Family. + * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma”, “verdana”.. + */ + indexLabelFontFamily?: string; + /** + * Sets the Index Label’s Font Weight. It can be set to one of the below options. + * Default: “normal” + * Example: “lighter”, “normal” ,”bold” , “bolder” + */ + indexLabelFontWeight?: string; + /** + * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. The value of indexLineColor can be a “HTML Color Name” or “Hex Code”. + * Default: “lightgrey” + * Example: “red”, “#FAC003″ .. + */ + indexLabelLineColor?: string; + /** + * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacement is set to “outside”. + * Default: 2 + * Example: 4, 6 + */ + indexLabelLineThickness?: string; + /** + * Default Tooltip can be modified at dataSeries or dataPoint level. You can add content to be displayed in toolTip using toolTipContent. toolTipContent set at dataPoint will override toolTipContent set at dataSeries level. + * Default: auto set depending on chart type. + */ + toolTipContent?: string; + /** + * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. + * Same marker type is also used in legend unless overridden by legendMarkerType property. + * Default: “circle” + * Options: “none”, “circle”, “square”, “triangle” and “cross” + */ + markerType?: string; + /** + * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. + * Default: dataSeries Color + * Example: “red”, “#008000″ .. + */ + markerColor?: string; + /** + * Sets the Size of the marker that is drawn. To display marker in area Chart, set markerSize to a value greater than zero. For line, scatter chart, size it is automatically set unless overridden. + * Default: auto. Zero for area chart + * Example: 5, 10.. + */ + markerSize?: number; + /** + * Sets the border color around marker. Value of markerBorderColor can be “HTML Color Name” or “hex code”. + * Default: dataSeries color. + * Example: “red”, “#008000″ .. + */ + markerBorderColor?: string; + /** + * Sets the thickness of the Marker’s Border in pixels. + * Default: 1 + * Example: 2,4 .. + */ + markerBorderThickness?: number; + /** + * Sets the text that describes the dataSeries in legend. + * Default: “DataSeries 1″, “DataSeries 2″ ..etc + * Example: “2010″, “2011″.. + */ + legendText?: string; + /** + * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. + * Default: same as markerType + * Options: “circle”, “square”, “cross” and “triangle” + */ + legendMarkerType?: string; + /** + * Sets the click event handler for dataSeries which is triggered when user clicks on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + click?: (event: ChartEvent) => void; + /** + * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. Value of legendMarkerColor can be “HTML Color Name” or “hex code”. + * Default: dataSeries marker color + * Example: “red”, “#008000″ .. + */ + legendMarkerColor?: string; + /** + * Sets the mouseover event handler for dataSeries which is triggered when user moves Mouse Over a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mouseover?: (event: ChartEvent) => void; + /** + * Sets the mousemove event handler for dataSeries which is triggered when user Moves mouse on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mousemove?: (event: ChartEvent) => void; + /** + * Sets the mouseout event handler for dataSeries which is triggered when user moves mouse out of a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mouseout?: (event: ChartEvent) => void; + } + + interface ChartDataOptions extends ChartDataCommon { + /** + * Sets the visibility of dataSeries. Data Series is visible by default and you can hide the same by setting visible property to false. + * Default: true + * Example: true, false + */ + visible?: boolean; + /** + * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. + * Default: “column” + * Options: + * “line” + * “column” + * “bar” + * “area” + * “spline” + * “splineArea” + * “stepLine” + * “scatter” + * “bubble” + * “stackedColumn” + * “stackedBar” + * “stackedArea” + * “stackedColumn100″ + * “stackedBar100″ + * “stackedArea100″ + * “pie” + * “doughnut” + */ + type?: string; + /** + * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing “secondary” Axis you can plot the series against axisY2. + * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. + * Default: “primary” + * Options: “primary”, “secondary” + */ + axisYType?: string; + /** + * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to “dateTime”. + * Default: Automatically Calculated + * Options: “number”, “dateTime” + */ + xValueType?: string; + /** + * Defines how y axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ + yValueFormatString?: string; + /** + * Defines how x axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ + xValueFormatString?: string; + /** + * Defines how z values is formatted before they appear on the indexLabel or toolTip. You can format numbers using this property. + */ + zValueFormatString?: string; + /** + * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. + * Default: “true” + * Example: “true”, “false” + */ + bevelEnabled?: boolean; + /** + * Sets opacity of the filled color. + * Default: .7 for Area Charts and 1 for all other chart types. + */ + fillOpacity?: number; + /** + * Sets the starting Angle of the Pie or Doughnut Chart in degrees. + * Default: 0 + * Example: 30, 240, -100.. + */ + startAngle?: number; + /** + * Sets the thickness of line in line charts and area charts. + * Default: 2 + * Example: 3,4.. + */ + lineThickness?: number; + /** + * Setting this property to true makes the dataSeries to appear in legend. In case of pie/ doughnut chart, dataPoints of the single series chart appear in legend. + * Default: false + * Options: false, true + */ + showInLegend?: boolean; + /** + * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. + * Default: “white” + * Options: “red”, “#DD7E86″, etc. + */ + risingColor?: string; + /** + * It represents collection dataPoint inside dataSeries . + */ + dataPoints: ChartDataPoint[]; + } + + interface ChartDataPoint extends ChartDataCommon { + /** + * Sets the x value. It determines the position of the dataPoint on X Axis. It can be numeric or a dateTime value. Values can be positive or Negative. + * Default: null + * Example: 10, 20, 30 .. + * new Date(2011, 08, 01) + */ + x?: any; + /** + * Sets the y value of dataPoint. It determines the position of dataPoint on Y Axis. Values can be positive or Negative + * Default: null + * Example: 5, 20, -30 .. + */ + y?: number; + /** + * Sets the z value of dataPoint. It is only applicable in case of Bubble chart. This value determines the size of the bubble. + * Default: 1 + * Example: 10, 20, 35.. + */ + z?: number; + /** + * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. + * Default: x value + * Example: “label1″, “label2″.. + */ + label?: string; + /** + * Sets the exploded value of dataPoint. It is applicable only in case of Pie and Doughnut Charts. This property causes the Pie/Doughnut slice to separate out. + * Default: true + * Example: true, false + */ + exploded?: boolean; + /** + * Sets the color of marker that is displayed on legend. This property works only with Pie and Doughnut charts. Value of legendMarkerColor can be “HTML Color Name” or “hex” code. + * Default: dataSeries marker color + * Example: “red”, “#008000″.. + */ + legendMarkerColor?: string; + } +} \ No newline at end of file diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts new file mode 100644 index 000000000..2374b6228 --- /dev/null +++ b/chartjs/chart-tests.ts @@ -0,0 +1,343 @@ +/// + +var canvas = document.getElementById('example-chart'); +var ctx = canvas.getContext('2d'); + +Chart.defaults.global = { + animation: true, + animationSteps: 60, + animationEasing: "easeOutQuart", + showScale: true, + scaleOverride: false, + scaleSteps: null, + scaleStepWidth: null, + scaleStartValue: null, + scaleLineColor: "rgba(0,0,0,.1)", + scaleLineWidth: 1, + scaleShowLabels: true, + scaleLabel: "<%=value%>", + scaleIntegersOnly: true, + scaleBeginAtZero: false, + scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + scaleFontSize: 12, + scaleFontStyle: "normal", + scaleFontColor: "#666", + responsive: false, + maintainAspectRatio: true, + showTooltips: true, + tooltipEvents: ["mousemove", "touchstart", "touchmove"], + tooltipFillColor: "rgba(0,0,0,0.8)", + tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + tooltipFontSize: 14, + tooltipFontStyle: "normal", + tooltipFontColor: "#fff", + tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + tooltipTitleFontSize: 14, + tooltipTitleFontStyle: "bold", + tooltipTitleFontColor: "#fff", + tooltipYPadding: 6, + tooltipXPadding: 6, + tooltipCaretSize: 8, + tooltipCornerRadius: 6, + tooltipXOffset: 10, + tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>", + multiTooltipTemplate: "<%= value %>", + onAnimationProgress: function () { }, + onAnimationComplete: function () { } +} + +var lineData: LinearChartData = { + labels: ['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00'], + datasets: [ + { + label: 'Accepted', + fillColor: 'rgba(220,220,220,0.2)', + strokeColor: 'rgba(220,220,220,1)', + pointColor: 'rgba(220,220,220,1)', + pointStrokeColor: '#fff', + pointHighlightFill: '#fff', + pointHighlightStroke: 'rgba(220,220,220,1)', + data: [65, 59, 80, 81, 56, 55, 40] + }, + { + label: 'Quarantined', + fillColor: 'rgba(151,187,205,0.2)', + strokeColor: 'rgba(151,187,205,1)', + pointColor: 'rgba(151,187,205,1)', + pointStrokeColor: '#fff', + pointHighlightFill: '#fff', + pointHighlightStroke: 'rgba(151,187,205,1)', + data: [28, 48, 40, 19, 86, 27, 90] + } + ] +}; + +var myLineChart = new Chart(ctx).Line(lineData, { + scaleShowGridLines: true, + scaleGridLineColor: "rgba(0,0,0,.05)", + scaleGridLineWidth: 1, + bezierCurve: true, + bezierCurveTension: 0.4, + pointDot: true, + pointDotRadius: 4, + pointDotStrokeWidth: 1, + pointHitDetectionRadius: 20, + datasetStroke: true, + datasetStrokeWidth: 2, + datasetFill: true, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" +}); + +var myLineChartLegend: string = myLineChart.generateLegend(); +var myLineChartImage: string = myLineChart.toBase64Image(); +myLineChart.addData([1, 2, 3, 4, 5, 6, 7], 'new'); +myLineChart.clear(); +myLineChart.removeData(); +myLineChart.resize(); +myLineChart.update(); +myLineChart.stop(); +myLineChart.destroy(); + +var barData: LinearChartData = { + labels: ["January", "February", "March", "April", "May", "June", "July"], + datasets: [ + { + label: "My First dataset", + fillColor: "rgba(220,220,220,0.5)", + strokeColor: "rgba(220,220,220,0.8)", + highlightFill: "rgba(220,220,220,0.75)", + highlightStroke: "rgba(220,220,220,1)", + data: [65, 59, 80, 81, 56, 55, 40] + }, + { + label: "My Second dataset", + fillColor: "rgba(151,187,205,0.5)", + strokeColor: "rgba(151,187,205,0.8)", + highlightFill: "rgba(151,187,205,0.75)", + highlightStroke: "rgba(151,187,205,1)", + data: [28, 48, 40, 19, 86, 27, 90] + } + ] +}; + +var myBarChart = new Chart(ctx).Bar(barData, { + scaleBeginAtZero: true, + scaleShowGridLines: true, + scaleGridLineColor: "rgba(0,0,0,.05)", + scaleGridLineWidth: 1, + barShowStroke: true, + barStrokeWidth: 2, + barValueSpacing: 5, + barDatasetSpacing: 1, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" +}); + +var myBarChartLegend: string = myBarChart.generateLegend(); +var myBarChartImage: string = myBarChart.toBase64Image(); +myBarChart.addData([1, 2, 3, 4, 5, 6, 7], 'new'); +myBarChart.clear(); +myBarChart.removeData(); +myBarChart.resize(); +myBarChart.update(); +myBarChart.stop(); +myBarChart.destroy(); + +var radarData: LinearChartData = { + labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], + datasets: [ + { + label: "My First dataset", + fillColor: "rgba(220,220,220,0.2)", + strokeColor: "rgba(220,220,220,1)", + pointColor: "rgba(220,220,220,1)", + pointStrokeColor: "#fff", + pointHighlightFill: "#fff", + pointHighlightStroke: "rgba(220,220,220,1)", + data: [65, 59, 90, 81, 56, 55, 40] + }, + { + label: "My Second dataset", + fillColor: "rgba(151,187,205,0.2)", + strokeColor: "rgba(151,187,205,1)", + pointColor: "rgba(151,187,205,1)", + pointStrokeColor: "#fff", + pointHighlightFill: "#fff", + pointHighlightStroke: "rgba(151,187,205,1)", + data: [28, 48, 40, 19, 96, 27, 100] + } + ] +}; + +var myRadarChart = new Chart(ctx).Radar(radarData, { + scaleShowLine: true, + angleShowLineOut: true, + scaleShowLabels: false, + scaleBeginAtZero: true, + angleLineColor: "rgba(0,0,0,.1)", + angleLineWidth: 1, + pointLabelFontFamily: "'Arial'", + pointLabelFontStyle: "normal", + pointLabelFontSize: 10, + pointLabelFontColor: "#666", + pointDot: true, + pointDotRadius: 3, + pointDotStrokeWidth: 1, + pointHitDetectionRadius: 20, + datasetStroke: true, + datasetStrokeWidth: 2, + datasetFill: true, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" +}); + +var myRadarChartLegend: string = myRadarChart.generateLegend(); +var myRadarChartImage: string = myRadarChart.toBase64Image(); +myRadarChart.addData([1, 2, 3, 4, 5, 6, 7], 'new'); +myRadarChart.clear(); +myRadarChart.removeData(); +myRadarChart.resize(); +myRadarChart.update(); +myRadarChart.stop(); +myRadarChart.destroy(); + +var polarAreaData: CircularChartData[] = [ + { + value: 300, + color: "#F7464A", + highlight: "#FF5A5E", + label: "Red" + }, + { + value: 50, + color: "#46BFBD", + highlight: "#5AD3D1", + label: "Green" + }, + { + value: 100, + color: "#FDB45C", + highlight: "#FFC870", + label: "Yellow" + }, + { + value: 40, + color: "#949FB1", + highlight: "#A8B3C5", + label: "Grey" + }, + { + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" + } + +]; + +var myPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, { + scaleShowLabelBackdrop: true, + scaleBackdropColor: "rgba(255,255,255,0.75)", + scaleBeginAtZero: true, + scaleBackdropPaddingY: 2, + scaleBackdropPaddingX: 2, + scaleShowLine: true, + segmentShowStroke: true, + segmentStrokeColor: "#fff", + segmentStrokeWidth: 2, + animationSteps: 100, + animationEasing: "easeOutBounce", + animateRotate: true, + animateScale: false, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
  • <%}%>
" +}); + +var myPolarAreaChartLegend: string = myPolarAreaChart.generateLegend(); +var myPolarAreaChartImage: string = myPolarAreaChart.toBase64Image(); +myPolarAreaChart.addData([{ + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" +}], 0); +myPolarAreaChart.clear(); +myPolarAreaChart.removeData(0); +myPolarAreaChart.resize(); +myPolarAreaChart.update(); +myPolarAreaChart.stop(); +myPolarAreaChart.destroy(); + +var pieData: CircularChartData[] = [ + { + value: 300, + color: "#F7464A", + highlight: "#FF5A5E", + label: "Red" + }, + { + value: 50, + color: "#46BFBD", + highlight: "#5AD3D1", + label: "Green" + }, + { + value: 100, + color: "#FDB45C", + highlight: "#FFC870", + label: "Yellow" + } +]; + +// For a pie chart +var myPieChart = new Chart(ctx).Pie(pieData, { + segmentShowStroke: true, + segmentStrokeColor: "#fff", + segmentStrokeWidth: 2, + percentageInnerCutout: 0, + animationSteps: 100, + animationEasing: "easeOutBounce", + animateRotate: true, + animateScale: false, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
  • <%}%>
" +}); + +var myPieChartLegend: string = myPieChart.generateLegend(); +var myPieChartImage: string = myPieChart.toBase64Image(); +myPieChart.addData([{ + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" +}], 0); +myPieChart.clear(); +myPieChart.removeData(0); +myPieChart.resize(); +myPieChart.update(); +myPieChart.stop(); +myPieChart.destroy(); + +// And for a doughnut chart +var myDoughnutChart = new Chart(ctx).Doughnut(pieData, { + segmentShowStroke: true, + segmentStrokeColor: "#fff", + segmentStrokeWidth: 2, + percentageInnerCutout: 50, + animationSteps: 100, + animationEasing: "easeOutBounce", + animateRotate: true, + animateScale: false, + legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(segments[i].label){%><%=segments[i].label%><%}%>
  • <%}%>
" +}); + +var myDoughnutChartLegend: string = myDoughnutChart.generateLegend(); +var myDoughnutChartImage: string = myDoughnutChart.toBase64Image(); +myPieChart.addData([{ + value: 120, + color: "#4D5360", + highlight: "#616774", + label: "Dark Grey" +}], 0); +myDoughnutChart.clear(); +myDoughnutChart.removeData(0); +myDoughnutChart.resize(); +myDoughnutChart.update(); +myDoughnutChart.stop(); +myDoughnutChart.destroy(); diff --git a/chartjs/chart.d.ts b/chartjs/chart.d.ts new file mode 100644 index 000000000..7364c6525 --- /dev/null +++ b/chartjs/chart.d.ts @@ -0,0 +1,205 @@ +// Type definitions for Chart.js +// Project: https://github.com/nnnick/Chart.js +// Definitions by: Steve Fenton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface ChartDataSet { + label: string; + fillColor: string; + strokeColor: string; + + /* Line, Radar */ + pointColor?: string; + pointStrokeColor?: string; + pointHighlightFill?: string; + pointHighlightStroke?: string; + + /* Bar */ + highlightFill?: string; + highlightStroke?: string; + data: number[]; +} + +interface LinearChartData { + labels: string[]; + datasets: ChartDataSet[]; +} + +interface CircularChartData { + value: number; + color: string; + highlight: string; + label: string; +} + +interface ChartSettings { + animation: boolean; + animationSteps: number; + animationEasing: string; + showScale: boolean; + scaleOverride: boolean; + scaleSteps: number; + scaleStepWidth: number; + scaleStartValue: number; + scaleLineColor: string; + scaleLineWidth: number; + scaleShowLabels: boolean; + scaleLabel: string; + scaleIntegersOnly: boolean; + scaleBeginAtZero: boolean; + scaleFontFamily: string; + scaleFontSize: number; + scaleFontStyle: string; + scaleFontColor: string; + responsive: boolean; + maintainAspectRatio: boolean; + showTooltips: boolean; + tooltipEvents: string[]; + tooltipFillColor: string; + tooltipFontFamily: string; + tooltipFontSize: number; + tooltipFontStyle: string; + tooltipFontColor: string; + tooltipTitleFontFamily: string; + tooltipTitleFontSize: number; + tooltipTitleFontStyle: string; + tooltipTitleFontColor: string; + tooltipYPadding: number; + tooltipXPadding: number; + tooltipCaretSize: number; + tooltipCornerRadius: number; + tooltipXOffset: number; + tooltipTemplate: string; + multiTooltipTemplate: string; + onAnimationProgress: () => any; + onAnimationComplete: () => any; +} + +interface ChartOptions { + scaleShowGridLines?: boolean; + scaleGridLineColor?: string; + scaleGridLineWidth?: number; + legendTemplate?: string; +} + +interface PointsAtEvent { + value: number; + label: string; + datasetLabel: string; + strokeColor: string; + fillColor: string; + highlightFill: string; + highlightStroke: string; + x: number; + y: number; +} + +interface ChartInstance { + clear: () => void; + stop: () => void; + resize: () => void; + destroy: () => void; + toBase64Image: () => string; + generateLegend: () => string; +} + +interface LinearInstance extends ChartInstance { + getPointsAtEvent: (event: Event) => PointsAtEvent[]; + update: () => void; + addData: (valuesArray: number[], label: string) => void; + removeData: () => void; +} + +interface CircularInstance extends ChartInstance { + getSegmentsAtEvent: (event: Event) => {}[]; + update: () => void; + addData: (valuesArray: CircularChartData[], index: number) => void; + removeData: (index: number) => void; +} + +interface LineChartOptions extends ChartOptions { + bezierCurve?: boolean; + bezierCurveTension?: number; + pointDot?: boolean; + pointDotRadius?: number; + pointDotStrokeWidth?: number; + pointHitDetectionRadius?: number; + datasetStroke?: boolean; + datasetStrokeWidth?: number; + datasetFill?: boolean; +} + +interface BarChartOptions extends ChartOptions { + scaleBeginAtZero?: boolean; + barShowStroke?: boolean; + barStrokeWidth?: number; + barValueSpacing?: number; + barDatasetSpacing?: number; +} + +interface RadarChartOptions { + scaleShowLine?: boolean; + angleShowLineOut?: boolean; + scaleShowLabels?: boolean; + scaleBeginAtZero?: boolean; + angleLineColor?: string; + angleLineWidth?: number; + pointLabelFontFamily?: string; + pointLabelFontStyle?: string; + pointLabelFontSize?: number; + pointLabelFontColor?: string; + pointDot?: boolean; + pointDotRadius?: number; + pointDotStrokeWidth?: number; + pointHitDetectionRadius?: number; + datasetStroke?: boolean; + datasetStrokeWidth?: number; + datasetFill?: boolean; + legendTemplate?: string; +} + +interface PolarAreaChartOptions { + scaleShowLabelBackdrop?: boolean; + scaleBackdropColor?: string; + scaleBeginAtZero?: boolean; + scaleBackdropPaddingY?: number; + scaleBackdropPaddingX?: number; + scaleShowLine?: boolean; + segmentShowStroke?: boolean; + segmentStrokeColor?: string; + segmentStrokeWidth?: number; + animationSteps?: number; + animationEasing?: string; + animateRotate?: boolean; + animateScale?: boolean; + legendTemplate?: string; +} + +interface PieChartOptions { + segmentShowStroke?: boolean; + segmentStrokeColor?: string; + segmentStrokeWidth?: number; + percentageInnerCutout?: number; + animationSteps?: number; + animationEasing?: string; + animateRotate?: boolean; + animateScale?: boolean; + legendTemplate?: string; +} + +interface Chart { + Line(data: LinearChartData, options?: LineChartOptions): LinearInstance; + Bar(data: LinearChartData, options?: BarChartOptions): LinearInstance; + Radar(data: LinearChartData, options?: RadarChartOptions): LinearInstance; + + PolarArea(data: CircularChartData[], options?: PolarAreaChartOptions): CircularInstance; + Pie(data: CircularChartData[], options?: PieChartOptions): CircularInstance; + Doughnut(data: CircularChartData[], options?: PieChartOptions): CircularInstance; +} + +declare var Chart: { + new (context: CanvasRenderingContext2D): Chart; + defaults: { + global: ChartSettings; + } +}; diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index af4b32046..08005eb67 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -806,4 +806,114 @@ declare module CodeMirror { By default, a marker appears only in its target document. */ shared?: boolean; } + + interface StringStream { + lastColumnPos: number; + lastColumnValue: number; + lineStart: number; + + /** + * Current position in the string. + */ + pos: number; + + /** + * Where the stream's position was when it was first passed to the token function. + */ + start: number; + + /** + * The current line's content. + */ + string: string; + + /** + * Number of spaces per tab character. + */ + tabSize: number; + + /** + * Returns true only if the stream is at the end of the line. + */ + eol(): boolean; + + /** + * Returns true only if the stream is at the start of the line. + */ + sol(): boolean; + + /** + * Returns the next character in the stream without advancing it. Will return an null at the end of the line. + */ + peek(): string; + + /** + * Returns the next character in the stream and advances it. Also returns null when no more characters are available. + */ + next(): string; + + /** + * match can be a character, a regular expression, or a function that takes a character and returns a boolean. + * If the next character in the stream 'matches' the given argument, it is consumed and returned. + * Otherwise, undefined is returned. + */ + eat(match: string): string; + eat(match: RegExp): string; + eat(match: (char: string) => boolean): string; + + /** + * Repeatedly calls eat with the given argument, until it fails. Returns true if any characters were eaten. + */ + eatWhile(match: string): boolean; + eatWhile(match: RegExp): boolean; + eatWhile(match: (char: string) => boolean): boolean; + + /** + * Shortcut for eatWhile when matching white-space. + */ + eatSpace(): boolean; + + /** + * Moves the position to the end of the line. + */ + skipToEnd(): void; + + /** + * Skips to the next occurrence of the given character, if found on the current line (doesn't advance the stream if + * the character does not occur on the line). + * + * Returns true if the character was found. + */ + skipTo(ch: string): boolean; + + /** + * Act like a multi-character eat - if consume is true or not given - or a look-ahead that doesn't update the stream + * position - if it is false. pattern can be either a string or a regular expression starting with ^. When it is a + * string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular + * expression, the returned value will be the array returned by match, in case you need to extract matched groups. + */ + match(pattern: string, consume?: boolean, caseFold?: boolean): boolean; + match(pattern: RegExp, consume?: boolean): string[]; + + /** + * Backs up the stream n characters. Backing it up further than the start of the current token will cause things to + * break, so be careful. + */ + backUp(n: number): void; + + /** + * Returns the column (taking into account tabs) at which the current token starts. + */ + column(): number; + + /** + * Tells you how far the current line has been indented, in spaces. Corrects for tab characters. + */ + indentation(): number; + + /** + * Get the string between the start of the current token and the current stream position. + */ + current(): string; + } } diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 3250f9c1e..6c7f356e6 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -841,6 +841,11 @@ declare module D3 { entries(values: any[]): NestKeyValue[]; } + export interface MapKeyValue { + key: string; + value: T; + } + export interface Map { has(key: string): boolean; get(key: string): T; @@ -848,7 +853,7 @@ declare module D3 { remove(key: string): boolean; keys(): string[]; values(): T[]; - entries(): any[][]; // Actually of form [key: string, val: T][], but this is inexpressible in Typescript + entries(): MapKeyValue[]; forEach(func: (key: string, value: T) => void ): void; empty(): boolean; size(): number; @@ -1902,13 +1907,13 @@ declare module D3 { /** * Get the accessor function that controls where the line is defined. */ - (): (data: any, index ?: number) => boolean; + (): (data: any, index?: number) => boolean; /** * Set the accessor function that controls where the area is defined. * * @param defined The new accessor function */ - (defined: (data: any) => boolean): Line; + (defined: (data: any, index?: number) => boolean): Line; }; } @@ -2198,13 +2203,13 @@ declare module D3 { /** * Get the accessor function that controls where the area is defined. */ - (): (data: any) => any; + (): (data: any, index?: number) => any; /** * Set the accessor function that controls where the area is defined. * * @param defined The new accessor function */ - (defined: (data: any) => any): Area; + (defined: (data: any, index?: number) => any): Area; }; } diff --git a/express/express.d.ts b/express/express.d.ts index 17c4ff36a..cf5014e82 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -424,7 +424,22 @@ declare module "express" { * @param code */ status(code: number): Response; - + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Send; + /** * Set Link header field with the given `links`. * diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index d532b1c56..81397ea4a 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -607,6 +607,21 @@ declare module fabric { loadFromDatalessJSON(json, callback: () => void): void; } + export interface IPattern { + (options: IPatternOptions): IPattern; + + initialise(options: IPatternOptions): IPattern; + + toLive(ctx: CanvasRenderingContext2D): IPattern; + toObject(): any; + toSVG(): string; + + offsetX: number; + offsetY: number; + repeat: string; + source: any; + } + export interface IBrightnessFilter { } export interface IInvertFilter { @@ -658,6 +673,13 @@ declare module fabric { stateful?: boolean; } + export interface IPatternOptions { + source: any; + offsetX: number; + offsetY: number; + repeat: string; + } + export interface IRectOptions extends IObjectOptions { x?: number; y?: number; @@ -697,6 +719,12 @@ declare module fabric { prototype: any; } + var Pattern: { + new (options: IPatternOptions): IPattern; + + prototype: any; + } + var Circle: { ATTRIBUTE_NAMES: string[]; fromElement(element: SVGElement, options: ICircleOptions): ICircle; diff --git a/fastclick/fastclick-tests.ts b/fastclick/fastclick-tests.ts new file mode 100644 index 000000000..0e31846ab --- /dev/null +++ b/fastclick/fastclick-tests.ts @@ -0,0 +1,22 @@ +/// + +// on browser +new FastClick(document.body); +new FastClick(document.getElementById('foo'), {tapDelay: 50}); +new FastClick(document.getElementsByTagName('p')[0], {touchBoundary: 50}); +var fc = FastClick.attach(document.body); +fc.determineEventType(document.getElementsByClassName('foo')).concat('bar'); +fc.findControl(document.querySelector('label')); +fc.focus(document.querySelectorAll('section')[0]); +document.body.addEventListener('click', function(e) { + fc.getTargetElementFromEventTarget(e.target); + fc.needsClick(e.target); + fc.needsFocus(e.target); +}); + +// on CommonJS environment +import fastclick = require('fastclick'); +fastclick(document.body); +new fastclick.FastClick(document.links[0]); +new fastclick.FastClick(document.links[1], {tapDelay: 50}); +new fastclick.FastClick(document.links[2], {touchBoundary: 50}); diff --git a/fastclick/fastclick.d.ts b/fastclick/fastclick.d.ts new file mode 100644 index 000000000..e90c3ac2e --- /dev/null +++ b/fastclick/fastclick.d.ts @@ -0,0 +1,44 @@ +// Type definitions for FastClick v1.0.3 +// Project: https://github.com/ftlabs/fastclick +// Definitions by: Shinnosuke Watanabe +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface FastClickObject { + lastTouchIdentifier: number; + layer: Element; + tapDelay: number; + targetElement: any; + touchBoundary: number; + touchStartX: number; + touchStartY: number; + trackingClick: boolean; + trackingClickStart: number; + destroy(): void; + determineEventType(targetElement: any): string; + findControl(labelElement: any /* EventTarget | HTMLLabelElement */): any; + focus(targetElement: any /* EventTarget | Element */): void; + getTargetElementFromEventTarget(eventTarget: EventTarget): any; + needsClick(target: any /* EventTarget | Element */): boolean; + needsFocus(target: any /* EventTarget | Element */): boolean; +} + +interface FastClickOptions { + touchBoundary?: number; + tapDelay?: number; +} + +interface FastClickStatic { + new(layer: any, options?: FastClickOptions): FastClickObject; + attach(layer: any, options?: FastClickOptions): FastClickObject; +} + +declare module "fastclick" { + function fastclick(layer: any, options?: FastClickOptions): FastClickObject; + module fastclick { + var FastClick: FastClickStatic; + } + + export = fastclick; +} + +declare var FastClick: FastClickStatic; diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 2657d8274..d9d53ab2b 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -14,8 +14,8 @@ declare module google { export interface ChartSpecs { chartType: string; - containerId: string; - oprtions?: Object; + containerId?: string; + options?: Object; dataTable?: Object; dataSourceUrl?: string; query?: string; @@ -75,7 +75,7 @@ declare module google { addRows(rows: DataObjectCell[][]): number; addRows(rows: any[][]): number; clone(): DataTable; - getColumnId(columnIndex: number): String; + getColumnId(columnIndex: number): string; getColumnLabel(columnIndex: number): string; getColumnPattern(columnIndex: number): string; getColumnProperties(columnIndex: number): Properties; @@ -445,8 +445,8 @@ declare module google { class ChartBase { constructor(element: Element); - getSelection(): any[]; - setSelection(selection: any[]): void; + getSelection(): VisualizationSelectionArray[]; + setSelection(selection: VisualizationSelectionArray[]): void; clearChart(): void; getImageURI(): string; } diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 27275f098..cf51d84c1 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1263,8 +1263,8 @@ declare module google.maps { } export class poly { - containsLocation(point: LatLng, polygon: Polygon): boolean; - isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): boolean; + static containsLocation(point: LatLng, polygon: Polygon): boolean; + static isLocationOnEdge(point: LatLng, poly: any, tolerance?: number): boolean; } } diff --git a/gulp/gulp-tests.ts b/gulp/gulp-tests.ts index 50ebeebf0..7e07f25f7 100644 --- a/gulp/gulp-tests.ts +++ b/gulp/gulp-tests.ts @@ -2,20 +2,28 @@ import gulp = require("gulp"); -var typescript: any = null; // this would be the TypeScript compiler -var jasmine: any = null; // this would be the jasmine test runner +var typescript: IGulpPlugin = null; // this would be the TypeScript compiler +var jasmine: IGulpPlugin = null; // this would be the jasmine test runner gulp.task('compile', function() { gulp.src("**/*.ts") - .pipe(typescript) - .dest('out') + .pipe(typescript()) + .pipe(gulp.dest('out')) }); -gulp.task('test', ['compile'], function() +gulp.task('compile2', function(callback: (err?: any) => void) +{ + gulp.src("**/*.ts") + .pipe(typescript()) + .pipe(gulp.dest('out')) + .on('end', callback); +}); + +gulp.task('test', ['compile', 'compile2'], function() { gulp.src("out/test/**/*.js") - .pipe(jasmine); + .pipe(jasmine()); }); gulp.task('default', ['compile', 'test']); diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 908fc4c27..7ec11def7 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -3,6 +3,8 @@ // Definitions by: Drew Noakes // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module gulp { /** @@ -171,15 +173,10 @@ declare module gulp { interface ITaskCallback { /** * Defines a task. - * Tasks may be made asynchronous if they return a promise or a stream. - */ - (): any; - - /** - * Defines an asynchronous task. + * Tasks may be made asynchronous if they are passing a callback or return a promise or a stream. * @param cb callback used to signal asynchronous completion. Caller includes err in case of error. */ - (cb:(err?:any)=>void): void; + (cb?:(err?:any)=>void): any; } interface EventEmitter { @@ -193,7 +190,7 @@ declare module gulp { * @param name the name of the task. Tasks that you want to run from the command line should not have spaces in them. * @param fn the function that performs the task's operations. Generally this takes the form of gulp.src().pipe(someplugin()). */ - task(name:string, fn:ITaskCallback): Gulp; + task(name:string, fn:ITaskCallback): any; /** * Define a task. @@ -202,7 +199,7 @@ declare module gulp { * @param dep an array of tasks to be executed and completed before your task will run. * @param fn the function that performs the task's operations. Generally this takes the form of gulp.src().pipe(someplugin()). */ - task(name:string, dep:string[], fn?:ITaskCallback): Gulp; + task(name:string, dep:string[], fn?:ITaskCallback): any; /** @@ -210,14 +207,14 @@ declare module gulp { * @param glob a glob string, using node-glob syntax * @param opt an optional option object */ - src(glob:string, opt?:ISrcOptions): Gulp; + src(glob:string, opt?:ISrcOptions): NodeJS.ReadWriteStream; /** * Takes a glob and represents a file structure. Can be piped to plugins. * @param glob an array of glob strings, using node-glob syntax * @param opt an optional option object */ - src(glob:string[], opt?:ISrcOptions): Gulp; + src(glob:string[], opt?:ISrcOptions): NodeJS.ReadWriteStream; /** @@ -227,7 +224,7 @@ declare module gulp { * @param outFolder the path (output folder) to write files to. * @param opt */ - dest(outFolder:string, opt?:IDestOptions): Gulp; + dest(outFolder:string, opt?:IDestOptions): NodeJS.ReadWriteStream; /** * Can be piped to and it will write files. Re-emits all data passed to it so you can pipe to multiple folders. @@ -236,16 +233,17 @@ declare module gulp { * @param outFolder a function that converts a vinyl File instance into an output path * @param opt */ - dest(outFolder:(file:string)=>string, opt?:IDestOptions): Gulp; + dest(outFolder:(file:string)=>string, opt?:IDestOptions): NodeJS.ReadWriteStream; /** - * Forwards the current Gulp instance, along with its contained files, to the specified receiver. + * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. * - * @param receiver the receiver + * @param glob a single glob or array of globs that indicate which files to watch for changes. + * @param tasks names of task(s) to run when a file changes, added with gulp.task() */ - pipe(receiver:any): Gulp; - + watch(glob:string, tasks:string[]): EventEmitter; + watch(glob:string[], tasks:string[]): EventEmitter; /** * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. @@ -284,3 +282,7 @@ declare module "gulp" { var _tmp:gulp.Gulp; export = _tmp; } + +interface IGulpPlugin { + (...args: any[]): NodeJS.ReadWriteStream; +} diff --git a/highlightjs/highlightjs-7.5.0.d.ts b/highlightjs/highlightjs-7.5.0.d.ts new file mode 100644 index 000000000..725f78fbc --- /dev/null +++ b/highlightjs/highlightjs-7.5.0.d.ts @@ -0,0 +1,82 @@ +// Type definitions for highlight.js v7.5.0 +// Project: https://github.com/isagalaev/highlight.js +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "highlight.js" +{ + module hljs + { + export var LANGUAGES: { [name: string] : any; }; + + export function blockText(block: Node, ignoreNewLines: boolean) : string; + export function blockLanguage(block: Node) : string; + + export function highlight(language_name: string, value: string) : IHighlightResult + export function highlightAuto(text: string) : IHighlightResult + + export function fixMarkup(value: string, tabReplace: boolean, useBR: boolean) : string; + + export function highlightBlock(block: Node, tabReplace?: boolean, useBR?: boolean) : void; + + export function initHighlighting(): void; + export function initHighlightingOnLoad(): void; + + export var tabReplace : string; + + // Common regexps + export var IDENT_RE: string; + export var UNDERSCORE_IDENT_RE: string; + export var NUMBER_RE: string; + export var C_NUMBER_RE: string; + export var BINARY_NUMBER_RE: string; + export var RE_STARTERS_RE: string; + + // Common modes + export var BACKSLASH_ESCAPE : IMode; + export var APOS_STRING_MODE : IMode; + export var QUOTE_STRING_MODE : IMode; + export var C_LINE_COMMENT_MODE : IMode; + export var C_BLOCK_COMMENT_MODE : IMode; + export var HASH_COMMENT_MODE : IMode; + export var NUMBER_MODE : IMode; + export var C_NUMBER_MODE : IMode; + export var BINARY_NUMBER_MODE : IMode; + + export interface IHighlightResult + { + relevance: number; + keyword_count: number; + value: string; + } + + export interface IAutoHighlightResult extends IHighlightResult + { + language: string; + second_best?: IAutoHighlightResult; + } + + // Reference: + // https://github.com/isagalaev/highlight.js/blob/master/docs/reference.rst + export interface IMode + { + className?: string; + begin: string; + end?: string; + beginWithKeyword?: boolean; + endsWithParent?: boolean; + lexems?: string; + keywords?: Object; + illegal?: string; + excludeBegin?: boolean; + excludeEnd?: boolean; + returnBegin?: boolean; + returnEnd?: boolean; + contains?: IMode[]; + starts?: string; + subLanguage?: string; + relevance?: number; + } + } + export = hljs; +} diff --git a/highlightjs/highlightjs-tests.ts b/highlightjs/highlightjs-tests.ts index 749be67cc..233d1fa3e 100644 --- a/highlightjs/highlightjs-tests.ts +++ b/highlightjs/highlightjs-tests.ts @@ -12,7 +12,7 @@ import hljs = require("highlight.js"); var code = "using System;\npublic class Test\n{\npublic static void Main()\n{\n// your code goes here\n}\n}"; var lang = "cs"; -hljs.tabReplace = " "; // 4 spaces +hljs.configure({ tabReplace: " " }); // 4 spaces var hl = hljs.highlight(lang, code).value; -hl = hljs.highlightAuto(code).value; \ No newline at end of file +hl = hljs.highlightAuto(code).value; diff --git a/highlightjs/highlightjs.d.ts b/highlightjs/highlightjs.d.ts index d730029b5..dc7606d88 100644 --- a/highlightjs/highlightjs.d.ts +++ b/highlightjs/highlightjs.d.ts @@ -1,28 +1,37 @@ -// Type definitions for highlight.js +// Type definitions for highlight.js v8.2.0 // Project: https://github.com/isagalaev/highlight.js -// Definitions by: Niklas Mollenhauer +// Definitions by: Niklas Mollenhauer , Jeremy Hull // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module "highlight.js" { module hljs { - export var LANGUAGES: { [name: string] : any; }; + export function highlight( + name: string, + value: string, + ignore_illegals?: boolean, + continuation?: boolean) : IHighlightResult; + export function highlightAuto( + value: string, + languageSubset?: string[]) : IAutoHighlightResult; - export function blockText(block: Node, ignoreNewLines: boolean) : string; - export function blockLanguage(block: Node) : string; + export function fixMarkup(value: string) : string; - export function highlight(language_name: string, value: string) : IHighlightResult - export function highlightAuto(text: string) : IHighlightResult + export function highlightBlock(block: Node) : void; - export function fixMarkup(value: string, tabReplace: boolean, useBR: boolean) : string; + export function configure(options: IOptions): void; - export function highlightBlock(block: Node, tabReplace?: boolean, useBR?: boolean) : void; - export function initHighlighting(): void; export function initHighlightingOnLoad(): void; - export var tabReplace : string; + export function registerLanguage( + name: string, + language: (hljs?: HLJSStatic) => IModeBase): void; + export function listLanguages(): string[]; + export function getLanguage(name: string): IMode; + + export function inherit(parent: Object, obj: Object): Object; // Common regexps export var IDENT_RE: string; @@ -36,46 +45,109 @@ declare module "highlight.js" export var BACKSLASH_ESCAPE : IMode; export var APOS_STRING_MODE : IMode; export var QUOTE_STRING_MODE : IMode; + export var PHRASAL_WORDS_MODE : IMode; export var C_LINE_COMMENT_MODE : IMode; export var C_BLOCK_COMMENT_MODE : IMode; export var HASH_COMMENT_MODE : IMode; export var NUMBER_MODE : IMode; export var C_NUMBER_MODE : IMode; export var BINARY_NUMBER_MODE : IMode; + export var CSS_NUMBER_MODE : IMode; + export var REGEX_MODE : IMode; + export var TITLE_MODE : IMode; + export var UNDERSCORE_TITLE_MODE : IMode; - export interface IHighlightResult + export interface IHighlightResultBase { relevance: number; - keyword_count: number; + language: string; value: string; } - export interface IAutoHighlightResult extends IHighlightResult + export interface IAutoHighlightResult extends IHighlightResultBase { - language: string; second_best?: IAutoHighlightResult; } + export interface IHighlightResult extends IHighlightResultBase + { + top: ICompiledMode; + } + + export interface HLJSStatic + { + inherit(parent: Object, obj: Object): Object; + + // Common regexps + IDENT_RE: string; + UNDERSCORE_IDENT_RE: string; + NUMBER_RE: string; + C_NUMBER_RE: string; + BINARY_NUMBER_RE: string; + RE_STARTERS_RE: string; + + // Common modes + BACKSLASH_ESCAPE : IMode; + APOS_STRING_MODE : IMode; + QUOTE_STRING_MODE : IMode; + PHRASAL_WORDS_MODE : IMode; + C_LINE_COMMENT_MODE : IMode; + C_BLOCK_COMMENT_MODE : IMode; + HASH_COMMENT_MODE : IMode; + NUMBER_MODE : IMode; + C_NUMBER_MODE : IMode; + BINARY_NUMBER_MODE : IMode; + CSS_NUMBER_MODE : IMode; + REGEX_MODE : IMode; + TITLE_MODE : IMode; + UNDERSCORE_TITLE_MODE : IMode; + } + // Reference: // https://github.com/isagalaev/highlight.js/blob/master/docs/reference.rst - export interface IMode + export interface IModeBase { className?: string; - begin: string; + aliases?: string[]; + begin?: string; end?: string; - beginWithKeyword?: boolean; + case_insensitive?: boolean; + beginKeyword?: string; endsWithParent?: boolean; lexems?: string; - keywords?: Object; illegal?: string; excludeBegin?: boolean; excludeEnd?: boolean; returnBegin?: boolean; returnEnd?: boolean; - contains?: IMode[]; starts?: string; subLanguage?: string; + subLanguageMode?: string; relevance?: number; + variants?: IMode[]; + } + + export interface IMode extends IModeBase + { + keywords?: any; + contains?: IMode[]; + } + + export interface ICompiledMode extends IModeBase + { + compiled: boolean; + contains?: ICompiledMode[]; + keywords?: Object; + terminators: RegExp; + terminator_end?: string; + } + + export interface IOptions + { + classPrefix?: string; + tabReplace?: string; + useBR?: boolean; + languages?: string[]; } } export = hljs; diff --git a/howlerjs/howler-tests.ts b/howlerjs/howler-tests.ts new file mode 100644 index 000000000..aff0df926 --- /dev/null +++ b/howlerjs/howler-tests.ts @@ -0,0 +1,35 @@ +/** + * howler-tests.ts + * Created by xperiments on 02/09/14. + */ +/// + + +Howler.codecs('ogg'); +Howler.iOSAutoEnable = true; +var sound = new Howl({ + urls: ['sound.mp3'] +}).play(); + + +var sound = new Howl({ + urls: ['sound.mp3', 'sound.ogg', 'sound.wav'], + autoplay: true, + loop: true, + volume: 0.5, + onend: function() { + console.log('Finished!'); + } +}); + +var sound = new Howl({ + urls: ['sounds.mp3', 'sounds.ogg'], + sprite: { + blast: [0, 1000], + laser: [2000, 3000], + winner: [4000, 7500] + } +}); + +// shoot the laser! +sound.play('laser'); \ No newline at end of file diff --git a/howlerjs/howler.d.ts b/howlerjs/howler.d.ts new file mode 100644 index 000000000..577c9fd78 --- /dev/null +++ b/howlerjs/howler.d.ts @@ -0,0 +1,73 @@ +// Type definitions for howler.js v1.1.25 +// Project: https://github.com/goldfire/howler.js +// Definitions by: Pedro Casaubon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare class HowlerGlobal { + mute(): HowlerGlobal; + unmute(): HowlerGlobal; + volume(): number; + volume(volume: number): HowlerGlobal; + codecs(extension: string): boolean; + iOSAutoEnable: boolean; +} + +declare var Howler: HowlerGlobal; + + +interface IHowlCallback { + (): void; +} +interface IHowlSoundSpriteDefinition { + [name: string]: number[] +} +interface IHowlProperties { + autoplay?: boolean; + buffer?: boolean; + format?: string; + loop?: boolean; + sprite?: IHowlSoundSpriteDefinition; + volume?: number; + urls?: string[]; + onend?: IHowlCallback; + onload?: IHowlCallback; + onloaderror?: IHowlCallback; + onpause?: IHowlCallback; + onplay?: IHowlCallback; +} + + +declare class Howl { + + autoplay: Boolean; + buffer: Boolean; + format: string; + rate: number; + model: string; + onend: IHowlCallback; + onload: IHowlCallback; + onloaderror: IHowlCallback; + onpause: IHowlCallback; + onplay: IHowlCallback; + constructor(properties: IHowlProperties); + play(sprite?: string, callback?: (soundId: number) => void): Howl; + pause(soundId?: number): Howl; + stop(soundId?: number): Howl; + mute(soundId?: number): Howl; + unmute(soundId?: number): Howl; + fade(from: number, to: number, duration: number, callback?: IHowlCallback, soundId?: number): Howl; + loop(): boolean; + loop(loop: boolean): Howl; + pos(position?: number, soundId?: number): number; + pos3d(x: number, y: number, z: number, soundId?: number): any; + sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition; + volume(): number; + volume(volume?: number, soundId?: number): Howl; + urls(): string[]; + urls(urls: string[]): Howl; + on(event: string, listener?: () => void): Howl; + off(event: string, listener?: () => void): Howl; + unload(): void; +} + diff --git a/i18n-node/i18n-node-tests.ts b/i18n-node/i18n-node-tests.ts new file mode 100644 index 000000000..f4403e5c1 --- /dev/null +++ b/i18n-node/i18n-node-tests.ts @@ -0,0 +1,140 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/mashpie/i18n-node. + */ + +/// +/// +/// + +import express = require("express"); +import i18n = require("i18n"); + +var app = express(); +var req: express.Request; + +/** + * Configuration + * https://github.com/mashpie/i18n-node#configure + */ +i18n.configure({ + locales: ['en', 'de'], + directory: __dirname + '/locales' +}); + +i18n.configure({ + // setup some locales - other locales default to en silently + locales: ['en', 'de'], + + // you may alter a site wide default locale + defaultLocale: 'de', + + // sets a custom cookie name to parse locale settings from - defaults to NULL + cookie: 'yourcookiename', + + // where to store json files - defaults to './locales' relative to modules directory + directory: './mylocales', + + // whether to write new locale information to disk - defaults to true + updateFiles: false, + + // what to use as the indentation unit - defaults to "\t" + indent: "\t", + + // setting extension of json files - defaults to '.json' (you might want to set this to '.js' according to webtranslateit) + extension: '.js', + + // setting prefix of json files name - default to none '' (in case you use different locale files naming scheme (webapp-en.json), rather then just en.json) + prefix: 'webapp-', + + // enable object notation + objectNotation: false +}); + +/** + * Usage in global scope + * https://github.com/mashpie/i18n-node#example-usage-in-global-scope + */ +var greeting = i18n.__('Hello'); + +/** + * Usage in Express + * https://github.com/mashpie/i18n-node#example-usage-in-expressjs + */ +// Configuration +app.configure(function () { + // default: using 'accept-language' header to guess language settings + app.use(i18n.init); +}); + +app.get('/de', function (_req, res) { + var greeting = res.__('Hello'); +}); + +/** + * __() + * https://github.com/mashpie/i18n-node#__ + */ +// global (this.locale == 'de') +i18n.__('Hello'); // Hallo +i18n.__('Hello %s', 'Marcus'); // Hallo Marcus +i18n.__('Hello {{name}}', { name: 'Marcus' }); // Hallo Marcus + +// scoped via req object (req.locale == 'de') +req.__('Hello'); // Hallo +req.__('Hello %s', 'Marcus'); // Hallo Marcus +req.__('Hello {{name}}', { name: 'Marcus' }); // Hallo Marcus + +// passing specific locale +i18n.__({ phrase: 'Hello', locale: 'fr' }); // Salut +i18n.__({ phrase: 'Hello %s', locale: 'fr' }, 'Marcus'); // Salut Marcus +i18n.__({ phrase: 'Hello {{name}}', locale: 'fr' }, { name: 'Marcus' }); // Salut Marcus + +/** + * __n() + * https://github.com/mashpie/i18n-node#__n + */ +// global (this.locale == 'de') +i18n.__n("%s cat", "%s cats", 1); // 1 Katze +i18n.__n("%s cat", "%s cats", 3); // 3 Katzen + +// scoped via req object (req.locale == 'de') +req.__n("%s cat", "%s cats", 1); // 1 Katze +req.__n("%s cat", "%s cats", 3); // 3 Katzen + +// passing specific locale +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr" }, 1); // 1 chat +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr" }, 3); // 3 chat +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr", count: 1 }); // 1 chat +i18n.__n({ singular: "%s cat", plural: "%s cats", locale: "fr", count: 3 }); // 3 chat + +/** + * setLocale() + * https://github.com/mashpie/i18n-node#setlocale + */ +i18n.setLocale('de'); +i18n.setLocale(req, 'de'); +req.setLocale('de'); + +/** + * getLocale() + * https://github.com/mashpie/i18n-node#getlocale + */ +i18n.getLocale(); // --> de +i18n.getLocale(req); // --> de +req.getLocale(); // --> de + +/** + * getCatalog() + * https://github.com/mashpie/i18n-node#getcatalog + */ +i18n.getCatalog(); // returns all locales +i18n.getCatalog('de'); // returns just 'de' + +i18n.getCatalog(req); // returns all locales +i18n.getCatalog(req, 'de'); // returns just 'de' + +req.getCatalog(); // returns all locales +req.getCatalog('de'); // returns just 'de' + diff --git a/i18n-node/i18n-node.d.ts b/i18n-node/i18n-node.d.ts new file mode 100644 index 000000000..348c2f268 --- /dev/null +++ b/i18n-node/i18n-node.d.ts @@ -0,0 +1,339 @@ +// Type definitions for i18n-node 0.5.0 +// Project: https://github.com/mashpie/i18n-node +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module i18n { + export interface ConfigurationOptions { + /** Setup some locales - other locales default to en silently */ + locales?: string[]; + /** Alter a site wide default locale */ + defaultLocale?: string; + + /** + * Sets a custom cookie name to parse locale settings from + * @default null + */ + cookie?: string; + /** + * Where to store json files, relative to modules directory + * @default "./locales" + */ + directory?: string; + + /** + * whether to write new locale information to disk + * @default true + */ + updateFiles?: boolean; + + /** + * What to use as the indentation unit + * @default "\t" + */ + indent?: string; + + /** + * Setting extension of json files (you might want to set this to '.js' according to webtranslateit) + * @default ".json" + */ + extension?: string; + + /** + * Enable object notation + * @default false + */ + objectNotation?: boolean; + } + export interface TranslateOptions { + phrase: string; + locale?: string; + } + export interface PluralOptions { + singular: string; + plural: string; + count?: number; + locale?: string; + } + export interface Replacements { + [key: string]: string; + } + + export interface LocaleCatalog { + [key: string]: string; + } + export interface GlobalCatalog { + [key: string]: LocaleCatalog; + } + + /** + * Configure current i18n instance + * @param {ConfigurationOptions} options - configuration options for i18n + */ + function configure(options: ConfigurationOptions): void; + + /** + * Initialize i18n middleware for express + * @param {Express.Request} request - Current express request + * @param {Express.Response} response - Current express response + * @param {Function} next - Callback to continue process + */ + function init(request: Express.Request, response: Express.Response, next?: Function): void; + + //#region __() + + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @returns {string} The translated phrase + */ + function __(phrase: string, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + function __(phrase: string, replacements: Replacements): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + function __(options: TranslateOptions): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + function __(options: TranslateOptions, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + function __(options: TranslateOptions, replacements: Replacements): string; + + //#endregion + + //#region __n() + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @returns {string} The translated phrase + */ + function __n(options: PluralOptions): string; + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + function __n(options: PluralOptions, count: number): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + function __n(singular: string, plural: string, count: number): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + function __n(singular: string, plural: string, count: string): string; + + //#endregion + + //#region Locale + + /** + * Change the current active locale + * @param {string} locale - The locale to set as default + */ + function setLocale(locale: string): void; + /** + * Change the current active locale for specified request + * @param {Express.Request} request - The request to change locale on + * @param {string} locale - The locale to set as default + */ + function setLocale(request: Express.Request, locale: string): void; + + /** + * Get the current active locale + * @returns {string} The current locale in request + */ + function getLocale(): string; + /** + * Get the current active locale for specified request + * @param {Express.Request} request - The request to get locale for + * @returns {string} The current locale in request + */ + function getLocale(request: Express.Request): string; + + //#endregion + + //#region Catalog + + /** + * Get the current global catalog + * @returns {GlobalCatalog} The current global catalog + */ + function getCatalog(): GlobalCatalog; + /** + * Get the catalog for the given locale + * @param {string} locale - The locale to get catalog for + * @returns {LocaleCatalog} The specified locale catalog + */ + function getCatalog(locale: string): LocaleCatalog; + /** + * Get the current active locale catalog for specified request + * @param {Express.Request} request - The request to get locale catalog for + * @returns {LocaleCatalog} The current locale catalog for the specified request + */ + function getCatalog(request: Express.Request): LocaleCatalog; + /** + * Get the current locale catalog for specified request and specified locale + * @param {Express.Request} request - The request to get locale catalog for + * @param {string} locale - The locale to get catalog for + * @returns {LocaleCatalog} The specified locale catalog + */ + function getCatalog(request: Express.Request, locale: string): LocaleCatalog; + + //#endregion + + /** + * Override the current request locale by using the query param (?locale=en) + * @param {Express.Request} [request] - The request to override locale for + */ + function overrideLocaleFromQuery(request?: Express.Request): void; + + /** + * Get current i18n-node version + * @member {string} + */ + var version: string; +} + +interface i18nAPI { + locale: string; + + //#region __() + + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @returns {string} The translated phrase + */ + __(phrase: string, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {string} phrase - The phrase to translate + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + __(phrase: string, replacements: i18n.Replacements): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + __(options: i18n.TranslateOptions): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @returns {string} The translated phrase + */ + __(options: i18n.TranslateOptions, ...replace: string[]): string; + /** + * Translate the given phrase using locale configuration + * @param {TranslateOptions} options - Options for translation + * @param {Object} replacements - An object containing replacements + * @returns {string} The translated phrase + */ + __(options: i18n.TranslateOptions, replacements: i18n.Replacements): string; + + //#endregion + + //#region __n() + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @returns {string} The translated phrase + */ + __n(options: i18n.PluralOptions): string; + + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {PluralOptions} options - Options for plural translate + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + __n(options: i18n.PluralOptions, count: number): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + __n(singular: string, plural: string, count: number): string; + /** + * Translate with plural condition the given phrase and count using locale configuration + * @param {string} singular - The singular pharse to translate if count is <= 1 + * @param {string} plural - The plural pharse to translate if count is > 1 + * @param {number} count - The number which allow to select from plural to singular + * @returns {string} The translated phrase + */ + __n(singular: string, plural: string, count: string): string; + + //#endregion + + /** + * Get the current active locale + * @returns {string} The current locale in request + */ + getLocale(): string; + /** + * Change the current active locale + * @param {string} locale - The locale to set as default + */ + setLocale(locale: string): void; + + /** + * Get the current global catalog + * @returns {GlobalCatalog} The current global catalog + */ + getCatalog(): i18n.GlobalCatalog; + /** + * Get the catalog for the given locale + * @param {string} locale - The locale to get catalog for + * @returns {LocaleCatalog} The specified locale catalog + */ + getCatalog(locale: string): i18n.LocaleCatalog; +} + +declare module "i18n" { + export = i18n; +} + +declare module Express { + export interface Request extends i18nAPI { + languages: string[]; + regions: string[]; + language: string; + region: string; + } + export interface Response extends i18nAPI { + locals: i18nAPI + } +} diff --git a/i18next/i18next-tests.ts b/i18next/i18next-tests.ts index f40d10b3a..b1732de11 100644 --- a/i18next/i18next-tests.ts +++ b/i18next/i18next-tests.ts @@ -6,7 +6,7 @@ /// declare function done(): void; - + describe('i18next', function () { var i18n = $.i18n @@ -685,6 +685,23 @@ describe('i18next', function () { }); }); + describe('exists functionality', function () { + var resStore = { + dev: { translation: { empty: '' } }, + en: { translation: {} }, + 'en-US': { translation: {} } + }; + + beforeEach(function (done) { + i18n.init($.extend(opts, { resStore: resStore }), + function (t) { done(); }); + }); + + it('it should be able to test if a key exists', function () { + expect(i18n.exists('empty')).to.be(false); + }); + }); + describe('resource string as array', function () { var resStore = { dev: { translation: { testarray: ["title", "text"] } }, diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index e9083c4d5..54bd439f4 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -109,6 +109,7 @@ interface I18nextStatic { }; t(key: string, options?: any): string; translate(key: string, options?: any): string; + exists(key: string, options?: any): boolean; } // jQuery extensions @@ -118,9 +119,9 @@ interface JQueryStatic { } interface JQuery { - /* Note: options are same options as used by the translate function. Alternatively by - setting init option or translation option 'useDataAttrOptions = true' the Options - for translation will be read and cached in the elements data-i18n-options attribute. + /* Note: options are same options as used by the translate function. Alternatively by + setting init option or translation option 'useDataAttrOptions = true' the Options + for translation will be read and cached in the elements data-i18n-options attribute. */ i18n: (options?: I18nextOptions) => void; } diff --git a/interactjs/interact-tests.ts b/interactjs/interact-tests.ts index e658f1275..b57a02c97 100644 --- a/interactjs/interact-tests.ts +++ b/interactjs/interact-tests.ts @@ -103,5 +103,6 @@ interact.deltaSource("page"); interact.restrict({ "drag": rectangle, "resize": rectangle, - "gesture": rectangle + "gesture": rectangle, + "elementRect": { top: 0, left: 0, bottom: 1, right: 1 } }); diff --git a/interactjs/interact.d.ts b/interactjs/interact.d.ts index 8189d6415..1ad864607 100644 --- a/interactjs/interact.d.ts +++ b/interactjs/interact.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Interacting for interact.js v1.0.17 +// Type definitions for Interacting for interact.js v1.0.25 // Project: https://github.com/taye/interact.js -// Definitions by: Douglas Eichelberger -// Definitions: https://github.com/borisyankov/DefinitelyType +// Definitions by: Douglas Eichelberger , Adi Dahiya +// Definitions: https://github.com/borisyankov/DefinitelyTyped // API documentation: http://interactjs.io/docs @@ -157,6 +157,7 @@ interface Restrict { drag?: any; gesture?: any; resize?: any; + elementRect?: {[direction: string]: number}; } interface InteractEvent { diff --git a/ip/ip-tests.ts b/ip/ip-tests.ts new file mode 100644 index 000000000..b852e08e7 --- /dev/null +++ b/ip/ip-tests.ts @@ -0,0 +1,19 @@ +/// + +import ip = require('ip'); + +var myIP = ip.address(); + +ip.cidr("192.168.0.1/24"); +ip.fromLong(ip.toLong(myIP)); +ip.fromPrefixLen(24); +ip.isEqual("192.168.0.1", myIP); +ip.isLoopback("127.0.0.1"); +ip.isPrivate(myIP); +ip.isPublic(myIP); +ip.loopback("ipv6"); +ip.mask("192.168.0.1", "255.255.255.0"); +ip.not("255.255.255.0"); +ip.or("192.168.0.1", "255.255.255.0"); +var buff:any = ip.toBuffer(myIP); +ip.toString(buff); \ No newline at end of file diff --git a/ip/ip.d.ts b/ip/ip.d.ts new file mode 100644 index 000000000..2fe3201c7 --- /dev/null +++ b/ip/ip.d.ts @@ -0,0 +1,91 @@ +// Type definitions for node-ip +// Project: https://github.com/indutny/node-ip +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface NodeBuffer { } + +declare module "ip" { + /** + * Check two IP address are the same. + **/ + export function isEqual(ip1: string, ip2: string): boolean; + + /** + * Convert an IP string into a buffer. + **/ + export function toBuffer(ip: string, buffer?: number, offset?: number): NodeBuffer; + + /** + * Convert an IP buffer into a string. + **/ + export function toString(ip: NodeBuffer, offset?: number, length?: number): string; + + /** + * Get the subnet mask from a CIDR prefix length. + * + * @param family The IP family is infered from the prefixLength, but can be explicity specified as either "ipv4" or "ipv6". + **/ + export function fromPrefixLen(prefixLength: number, family?:string): string; + + /** + * Get the network ID IP address from an IP address and its subnet mask. + **/ + export function mask(ip: string, mask: string): string; + + /** + * Get the network ID IP address from an IP address in CIDR notation. + **/ + export function cidr(cidr: string): string; + + /** + * Get the bitwise inverse (NOT every octet) of an IP address or subnet mask. + **/ + export function not(ip: string): string; + + /** + * Get the bitwise OR of two IP addresses (usually an IP address and a subnet mask). + **/ + export function or(ip: string, mask:string): string; + + /** + * Check whether an IP is within a private IP address range. + **/ + export function isPrivate(ip: string): boolean; + + /** + * Check whether an IP is within a public IP address range. + **/ + export function isPublic(ip: string): boolean; + + /** + * Check whether an IP is a loopback address. + **/ + export function isLoopback(ip: string): boolean; + + /** + * Get the loopback address for an IP family. + * + * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". + **/ + export function loopback(family?: string): string; + + /** + * Get the address for the network interface on the current system with the specified 'name'. + * If no interface name is specified, the first IPv4 address or loopback address is returned. + * + * @param name The name can be any named interface, or 'public' or 'private'. + * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". + **/ + export function address(name?: string, family?: string):string; + + /** + * Convert a string IPv4 IP address to the equivalent long numeric value. + **/ + export function toLong(ip: string): number; + + /** + * Convert an IPv4 IP address from its the long numeric value to a string. + **/ + export function fromLong(ip: number): string; +} \ No newline at end of file diff --git a/jquery.pjax/jquery.pjax-tests.ts b/jquery.pjax/jquery.pjax-tests.ts index 214bb3922..7b08ca6c4 100644 --- a/jquery.pjax/jquery.pjax-tests.ts +++ b/jquery.pjax/jquery.pjax-tests.ts @@ -39,7 +39,7 @@ function test_disable() { } function test_reload() { - $.pjax.reload(); + $.pjax.reload("#pjax-container"); } function test_defauluts() { diff --git a/jquery.pjax/jquery.pjax.d.ts b/jquery.pjax/jquery.pjax.d.ts index 621d87d21..48e48bcac 100644 --- a/jquery.pjax/jquery.pjax.d.ts +++ b/jquery.pjax/jquery.pjax.d.ts @@ -131,7 +131,7 @@ interface PjaxStatic { /** * Reload current page with pjax. */ - reload(): JQueryXHR; + reload(container: string, options?: PjaxSettings): JQueryXHR; } interface JQuerySupport { diff --git a/jsonwebtoken/jsonwebtoken-tests.ts b/jsonwebtoken/jsonwebtoken-tests.ts new file mode 100644 index 000000000..52f116335 --- /dev/null +++ b/jsonwebtoken/jsonwebtoken-tests.ts @@ -0,0 +1,64 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/auth0/node-jsonwebtoken. + */ + +/// +/// + +import jwt = require("jsonwebtoken"); +import fs = require("fs"); + +var token: string; +var cert: Buffer; + +/** + * jwt.sign + * https://github.com/auth0/node-jsonwebtoken#usage + */ +// sign with default (HMAC SHA256) +token = jwt.sign({ foo: 'bar' }, 'shhhhh'); + +// sign with RSA SHA256 +cert = fs.readFileSync('private.key'); // get private key +token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'}); + +/** + * jwt.verify + * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback + */ +// verify a token symmetric +jwt.verify(token, 'shhhhh', function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// invalid token +jwt.verify(token, 'wrong-secret', function(err, decoded) { + // err + // decoded undefined +}); + +// verify a token asymmetric +cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, function(err, decoded) { + console.log(decoded.foo) // bar +}); + +// verify audience +cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) { + // if audience mismatch, err == invalid audience +}); + +// verify issuer +cert = fs.readFileSync('public.pem'); // get public key +jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) { + // if issuer mismatch, err == invalid issuer +}); + +/** + * jwt.decode + * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken + */ +var decoded = jwt.decode(token); diff --git a/jsonwebtoken/jsonwebtoken.d.ts b/jsonwebtoken/jsonwebtoken.d.ts new file mode 100644 index 000000000..4deaf36ce --- /dev/null +++ b/jsonwebtoken/jsonwebtoken.d.ts @@ -0,0 +1,79 @@ +// Type definitions for jsonwebtoken 0.4.0 +// Project: https://github.com/auth0/node-jsonwebtoken +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "jsonwebtoken" { + + export interface SignOptions { + /** + * Signature algorithm. Could be one of these values : + * - HS256: HMAC using SHA-256 hash algorithm + * - HS384: HMAC using SHA-384 hash algorithm + * - HS512: HMAC using SHA-512 hash algorithm + * - RS256: RSASSA using SHA-256 hash algorithm + * - RS384: RSASSA using SHA-384 hash algorithm + * - RS512: RSASSA using SHA-512 hash algorithm + * - ES256: ECDSA using P-256 curve and SHA-256 hash algorithm + * - ES384: ECDSA using P-384 curve and SHA-384 hash algorithm + * - ES512: ECDSA using P-521 curve and SHA-512 hash algorithm + * - none: No digital signature or MAC value included + */ + algorithm?: string; + /** @member {number} - Lifetime for the token in minutes */ + expiresInMinutes?: number; + audience?: string; + subject?: string; + issuer?: string; + } + + export interface VerifyOptions { + audience?: string; + issuer?: string; + } + + export interface VerifyCallbak { + (err: Error, decoded: any): void; + } + + /** + * Sign the given payload into a JSON Web Token string + * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string + * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * @param {SignOptions} [options] - Options for the signature + * @returns {String} The JSON Web Token string + */ + export function sign(payload: string, secretOrPrivateKey: string): string; + export function sign(payload: string, secretOrPrivateKey: Buffer): string; + export function sign(payload: Buffer, secretOrPrivateKey: string): string; + export function sign(payload: Buffer, secretOrPrivateKey: Buffer): string; + export function sign(payload: Object, secretOrPrivateKey: string): string; + export function sign(payload: Object, secretOrPrivateKey: Buffer): string; + export function sign(payload: string, secretOrPrivateKey: string, options: SignOptions): string; + export function sign(payload: string, secretOrPrivateKey: Buffer, options: SignOptions): string; + export function sign(payload: Buffer, secretOrPrivateKey: string, options: SignOptions): string; + export function sign(payload: Buffer, secretOrPrivateKey: Buffer, options: SignOptions): string; + export function sign(payload: Object, secretOrPrivateKey: string, options: SignOptions): string; + export function sign(payload: Object, secretOrPrivateKey: Buffer, options: SignOptions): string; + + /** + * Verify given token using a secret or a public key to get a decoded token + * @param {String} token - JWT string to verify + * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * @param {VerifyOptions} [options] - Options for the verification + * @param {Function} callback - Callback to get the decoded token on + */ + function verify(token: string, secretOrPublicKey: string, callback: VerifyCallbak): void; + function verify(token: string, secretOrPublicKey: Buffer, callback: VerifyCallbak): void; + function verify(token: string, secretOrPublicKey: string, options: VerifyOptions, callback: VerifyCallbak): void; + function verify(token: string, secretOrPublicKey: Buffer, options: VerifyOptions, callback: VerifyCallbak): void; + + /** + * Returns the decoded payload without verifying if the signature is valid. + * @param {String} token - JWT string to decode + * @returns {Object} The decoded Token + */ + function decode(token: string): any; +} diff --git a/jstree/jstree-tests.ts b/jstree/jstree-tests.ts index ce8280721..aa834e621 100644 --- a/jstree/jstree-tests.ts +++ b/jstree/jstree-tests.ts @@ -69,6 +69,12 @@ var advancedTree = $("#briefcasetree").jstree({ var a = $('a').jstree(); +// test search node +a.search('test', false, true); + +//test redraw node +a.redraw_node($('#node1'), false, false, false); + //tree with new unique plugin parameters var treeWithUnique = $('#treeWithUnique').jstree({ diff --git a/jstree/jstree.d.ts b/jstree/jstree.d.ts index 10eff8d75..28297e555 100644 --- a/jstree/jstree.d.ts +++ b/jstree/jstree.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jsTree v3.0.3 +// Type definitions for jsTree v3.0.4 // Project: http://www.jstree.com/ // Definitions by: Adam Pluciński // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -555,8 +555,9 @@ interface JSTreeStaticDefaultsSearch { case_sensitive: boolean; /** - * Indicates if the tree should be filtered to show only matching nodes - * (keep in mind this can be a heavy on large trees in old browsers). Default is `false`. + * Indicates if the tree should be filtered (by default) to show only matching nodes + * (keep in mind this can be a heavy on large trees in old browsers). + * This setting can be changed at runtime when calling the search method. Default is `false`. * @name $.jstree.defaults.search.show_only_matches * @plugin search */ @@ -1183,8 +1184,15 @@ interface JSTree extends JQuery { show_icon: (obj: any) => void; /** + * redraws a single node. Used internally. + * @private + * @name redraw_node(node, deep, is_callback) + * @param {mixed} node the node to redraw + * @param {Boolean} deep should child nodes be redrawn too + * @param {Boolean} is_callback is this a recursion call + * @param {Boolean} force_render should children of closed parents be drawn anyway */ - redraw_node: (obj: any, deep: boolean, is_callback: boolean) => any; + redraw_node: (obj: any, deep?: boolean, is_callback?: boolean, force_render?: boolean) => any; /** * show the node checkbox icons @@ -1308,10 +1316,11 @@ interface JSTree extends JQuery { * @name search(str [, skip_async]) * @param {String} str the search string * @param {Boolean} skip_async if set to true server will not be queried even if configured + * @param {Boolean} show_only_matches if set to true only matching nodes will be shown (keep in mind this can be very slow on large trees or old browsers) * @plugin search * @trigger search.jstree */ - search: (str: string, skip_async?: boolean) => void; + search: (str: string, skip_async?: boolean, show_only_matches?: boolean) => void; /** * used to clear the last search (removes classes and shows all nodes if filtering is on) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 27487c7a6..8fc87e98d 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -161,6 +161,7 @@ interface KnockoutBindingHandlers { enable: KnockoutBindingHandler; disable: KnockoutBindingHandler; value: KnockoutBindingHandler; + textInput: KnockoutBindingHandler; hasfocus: KnockoutBindingHandler; checked: KnockoutBindingHandler; options: KnockoutBindingHandler; @@ -556,7 +557,13 @@ interface KnockoutBindingProvider { } interface KnockoutComponents { - register(componentName: string, definition: KnockoutComponentDefinition): void; + // overloads for register method: + register(componentName: string, config: KnockoutComponentRegister): void; + register(componentName: string, config: KnockoutComponentRegisterStringTemplate): void; + register(componentName: string, config: KnockoutComponentRegisterFnViewModel): void; + register(componentName: string, config: KnockoutComponentRegisterStringTemplateFnViewModel): void; + register(componentName: string, config: KnockoutComponentRegisterAMD): void; + isRegistered(componentName: string): boolean; unregister(componentName: string): void; get(componentName: string, callback: (definition: KnockoutComponentDefinition) => void): void; @@ -566,6 +573,50 @@ interface KnockoutComponents { getComponentNameForNode(node: Node): string; } +/* interfaces for register overloads*/ + +interface KnockoutComponentRegister { + template: KnockoutComponentTemplate; + viewModel?: KnockoutComponentConfigViewModel; +} + +interface KnockoutComponentRegisterAMD { + // load self-describing module using AMD module name + require: string; +} + +interface KnockoutComponentRegisterFnViewModel { + template: KnockoutComponentTemplate; + viewModel?: (params: any) => any; +} + +interface KnockoutComponentRegisterStringTemplate { + template: string; + viewModel?: KnockoutComponentConfigViewModel; +} + +interface KnockoutComponentRegisterStringTemplateFnViewModel { + template: string; + viewModel?: (params: any) => any; +} + +interface KnockoutComponentConfigViewModel { + instance?: any; + createViewModel? (params?: any, componentInfo?: KnockoutComponentInfo): any; + require?: string; +} + +interface KnockoutComponentTemplate { + // specify element id (string) or a node + element?: any; + // AMD module load + require?: string; +} + +interface KnockoutComponentInfo { + element: any; +} +/* end register overloads */ interface KnockoutComponentDefinition { template: Node[]; createViewModel?(params: any, options: { element: Node; }): any; diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 6d4c9e25d..82b5aa25c 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -602,4 +602,49 @@ function test_allBindingsAccessor() { var fnAccessorBinding = allBindingsAccessor().myBindingName; } }; +} + +function test_Components() { + + function test_Register() { + // test all possible ko.components.register() overloads + var nodeArray = [new Node, new Node]; + var singleNode = new Node; + + // ------- string-templates with different viewmodel overloads: + + // string template and inline function (commonly used in examples) + ko.components.register("name", { template: "string-template", viewModel: function (params) { return null; } }); + + // string template and instance vm + ko.components.register("name", { template: "string-template", viewModel: { instance: null } }); + + // string template and createViewModel factory method + ko.components.register("name", { template: "string-template", viewModel: { createViewModel: function (params: any, componentInfo: KnockoutComponentInfo) { return null; } } }); + + // string template and require module vm + ko.components.register("name", { template: "string-template", viewModel: { require: "module" } }); + + // ------- non-string templates + + // viewmodel as function and four types of template + ko.components.register("name", { template: { element: "elementID" }, viewModel: function (params) { return null; } }); + // Node template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { element: singleNode }, viewModel: function (params) { return null; } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: nodeArray, viewModel: function (params) { return null; } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { require: "module" }, viewModel: function (params) { return null; } }); + + // viewmodel as object, and four types of non-string tempalte + ko.components.register("name", { template: { element: "elementID" }, viewModel: { instance: null } }); + // Node template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { element: singleNode }, viewModel: { instance: null } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: nodeArray, viewModel: { instance: null } }); + // object template for element and inline function (commonly used in examples) + ko.components.register("name", { template: { require: "module" }, viewModel: { instance: null } }); + + // + } } \ No newline at end of file diff --git a/knockstrap/knockstrap-tests.ts b/knockstrap/knockstrap-tests.ts new file mode 100644 index 000000000..233ce6f4d --- /dev/null +++ b/knockstrap/knockstrap-tests.ts @@ -0,0 +1,43 @@ +/// +/// +/// +/// + + +// test unique id +var adaskoUnitqueId: string = ko.utils.uniqueId('adaskothebeast'); + +class Sample { + public property1: KnockoutObservable; + + constructor() { + this.property1 = ko.observable('test'); + } +} + +var sample = new Sample(); + +// test unwrap properties +var unwrappedProperties = ko.utils.unwrapProperties(sample); + +var kts: KnockoutTemplateSources; +var stringTemplate = kts.stringTemplate('string-template'); +var stname = stringTemplate.templateName; + +ko.stringTemplateEngine.instance.allowTemplateRewriting = true; + +var templateSource = ko.stringTemplateEngine.instance.makeTemplateSource('template'); +ko.stringTemplateEngine.instance.addTemplate('test', {}); +ko.stringTemplateEngine.instance.removeTemplate('test'); +ko.stringTemplateEngine.instance.isTemplateExist('test'); + + +var alertbh = ko.bindingHandlers.alert; +var carouselbh = ko.bindingHandlers.carousel; +var checkboxbh = ko.bindingHandlers.checkbox; +var modalbh = ko.bindingHandlers.modal; +var popoverbh = ko.bindingHandlers.popover; +var progressbh = ko.bindingHandlers.progress; +var radiobh = ko.bindingHandlers.radio; +var togglebh = ko.bindingHandlers.toggle; +var tooltipbh = ko.bindingHandlers.tooltip; \ No newline at end of file diff --git a/knockstrap/knockstrap.d.ts b/knockstrap/knockstrap.d.ts new file mode 100644 index 000000000..a1f9791da --- /dev/null +++ b/knockstrap/knockstrap.d.ts @@ -0,0 +1,163 @@ +// Type definitions for Knockstrap +// Project: http://faulknercs.github.io/Knockstrap/ +// Definitions by: Adam Pluciński +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +interface KnockoutUtils { + uniqueId(prefix: string): string; + unwrapProperties(wrappedProperies: any): any; +} + +interface KnockoutTemplateSources { + stringTemplate: { + prototype: KnockstrapStringTemplate; + new (template: string): KnockstrapStringTemplate; + }; +} + +interface KnockstrapStringTemplate extends KnockoutTemplateSourcesDomElement { + templateName: string; +} + +interface KnockoutStatic { + stringTemplateEngine: { + prototype: KnockstrapStringTemplateEngine; + new (): KnockstrapStringTemplateEngine; + instance: KnockstrapStringTemplateEngine; + } +} + +interface KnockstrapStringTemplateEngine extends KnockoutNativeTemplateEngine { + allowTemplateRewriting: boolean; + makeTemplateSource(template: string): KnockstrapStringTemplate; + addTemplate(name: string, template: any): void; + removeTemplate(name: string): void; + isTemplateExist(name: string): boolean; + getTemplate(name: string): any; +} + +interface KnockoutBindingHandlers { + alert: AlertKnockoutBindingHandler; + carousel: CarouselKnockoutBindingHandler; + checkbox: KnockoutBindingHandler; + modal: ModalKnockoutBindingHandler; + popover: PopoverKnockoutBindingHandler; + progress: ProgressKnockoutBindingHandler; + radio: KnockoutBindingHandler; + toggle: KnockoutBindingHandler; + tooltip: KnockoutBindingHandler; +} + +interface KnockoutControlsDescendantBindings { + controlsDescendantBindings: boolean; +} + +interface AlertKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; +} + +interface CarouselKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; + defaults: KnockstrapCarouselDefaults; +} + +interface KnockstrapCarouselDefaults { + css: string; + controlsTemplate: KnockstrapCarouselDefaultsControlsTemplate; + indicatorsTemplate: KnockstrapCarouselDefaultsIndicatorsTemplate; + itemTemplate: KnockstrapCarouselDefaultsItemTemplate; +} + +interface KnockstrapDefaultsTemplateBase { + name: string; + templateEngine: KnockstrapStringTemplateEngine; +} + +interface KnockstrapCarouselDefaultsControlsTemplate extends KnockstrapDefaultsTemplateBase { + dataConverter(value: any): KnockstrapCarouselDefaultsIdDataConverted; + +} + +interface KnockstrapCarouselDefaultsIdDataConverted { + id: KnockoutComputed; +} + +interface KnockstrapCarouselDefaultsIndicatorsTemplate extends KnockstrapDefaultsTemplateBase { + dataConverter(value: any): KnockstrapCarouselDefaultsIdItemsDataConverted; +} + +interface KnockstrapCarouselDefaultsIdItemsDataConverted extends KnockstrapCarouselDefaultsIdDataConverted { + items: any; +} + +interface KnockstrapCarouselDefaultsItemTemplate extends KnockstrapDefaultsTemplateBase { + converter(value: any): any; +} + +interface ModalKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; + defaults: KnockstrapModalDefaults; +} + +interface KnockstrapModalDefaults { + css: string; + attributes: KnockstrapModalDefaultsAttributes; + headerTemplate: KnockstrapDefaultsTemplateBase; + bodyTemplate: KnockstrapDefaultsTemplateBase; + footerTemplate: KnockstrapModalDefaultsFooterTemplate; +} + +interface KnockstrapModalDefaultsAttributes { + role: string; +} + +interface KnockstrapModalDefaultsFooterTemplate extends KnockstrapDefaultsTemplateBase { + data: KnockstrapModalDefaultsFooterData; +} + +interface KnockstrapModalDefaultsFooterData { + closeLabel: string; + primaryLabel: string; +} + +interface PopoverKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; +} + +interface ProgressKnockoutBindingHandler extends KnockoutBindingHandler { + init? (element: any, + valueAccessor: () => any, + allBindingsAccessor: KnockoutAllBindingsAccessor, + viewModel: any, + bindingContext: KnockoutBindingContext): KnockoutControlsDescendantBindings; + defaults: KnockstrapProgressDefaults; +} + +interface KnockstrapProgressDefaults { + css: string; + text: string; + textHidden: boolean; + striped: boolean; + type: string; + animated: boolean; +} \ No newline at end of file diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index 0c0b56784..14376f2b4 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -18,7 +18,7 @@ var now = moment(); var day7 = moment([2010, 1, 14, 15, 25, 50, 125]); var day8 = moment([2010]); var day9 = moment([2010, 6]); -var day10 = moment([2010, 6, 10]); +var day10 = moment([2010, 6, 10]); var array = [2010, 1, 14, 15, 25, 50, 125]; var day11 = moment(Date.UTC.apply({}, array)); var day12 = moment.unix(1318781876); @@ -62,8 +62,8 @@ a.hours(); a.local(); a.hours(); -moment("2011-10-10", "YYYY-MM-DD").isValid(); -moment("2011-10-50", "YYYY-MM-DD").isValid(); +moment("2011-10-10", "YYYY-MM-DD").isValid(); +moment("2011-10-50", "YYYY-MM-DD").isValid(); moment("2011-10-10T10:20:90").isValid(); moment([2011, 0, 1]).isValid(); moment([2011, 0, 50]).isValid(); @@ -74,32 +74,39 @@ moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).sec moment().add('days', 7); moment().add('days', 7).add('months', 1); moment().add({days:7,months:1}); -moment().add('milliseconds', 1000000); +moment().add('milliseconds', 1000000); moment().add('days', 360); -moment([2010, 0, 31]); +moment([2010, 0, 31]); moment([2010, 0, 31]).add('months', 1); var m = moment(new Date(2011, 2, 12, 5, 0, 0)); -m.hours(); +m.hours(); m.add('days', 1).hours(); -var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); +var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); m2.hours(); -m2.add('hours', 24).hours(); +m2.add('hours', 24).hours(); var duration = moment.duration({'days': 1}); moment([2012, 0, 31]).add(duration); +moment().add('seconds', 1); +moment().add('seconds', '1'); +moment().add(1, 'seconds'); + +moment().add('1', 'seconds'); +moment().add('seconds', '1'); + moment().subtract('days', 7); moment().seconds(30); moment().minutes(30); -moment().hours(12); +moment().hours(12); moment().date(5); moment().day(5); moment().day("Sunday"); moment().month(5); moment().month("January"); moment().year(1984); -moment().startOf('year'); +moment().startOf('year'); moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0); moment().startOf('hour'); moment().minutes(0).seconds(0).milliseconds(0); @@ -120,10 +127,10 @@ moment().isoWeek(45); moment().isoWeeks(); moment().isoWeeks(45); -var getMilliseconds: number = moment().milliseconds(); -var getSeconds: number = moment().seconds(); -var getMinutes: number = moment().minutes(); -var getHours: number = moment().hours(); +var getMilliseconds: number = moment().milliseconds(); +var getSeconds: number = moment().seconds(); +var getMinutes: number = moment().minutes(); +var getHours: number = moment().hours(); var getDate: number = moment().date(); var getDay: number = moment().day(); var getMonth: number = moment().month(); @@ -138,11 +145,11 @@ a3.utc(); a3.hours(); var a4 = moment([2010, 1, 14, 15, 25, 50, 125]); -a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); +a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); a4.format("ddd, hA"); moment().format('\\L'); -moment().format('[today] DDDD'); +moment().format('[today] DDDD'); var a5 = moment([2007, 0, 29]); var b5 = moment([2007, 0, 28]); @@ -151,8 +158,8 @@ a5.from(b5); var a6 = moment([2007, 0, 29]); var b6 = moment([2007, 0, 28]); a6.from(b6); -a6.from([2007, 0, 28]); -a6.from(new Date(2007, 0, 28)); +a6.from([2007, 0, 28]); +a6.from(new Date(2007, 0, 28)); a6.from("1-28-2007"); var a7 = moment(); @@ -161,23 +168,23 @@ a7.from(b7); var start = moment([2007, 0, 5]); var end = moment([2007, 0, 10]); -start.from(end); +start.from(end); start.from(end, true); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(true); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(true); var a8 = moment([2007, 0, 29]); var b8 = moment([2007, 0, 28]); a8.diff(b8) ; a8.diff(b8, 'days'); -a8.diff(b8, 'years') +a8.diff(b8, 'years') a8.diff(b8, 'years', true); moment([2007, 0, 29]).toDate(); moment([2007, 1, 23]).toISOString(); -moment(1318874398806).valueOf(); +moment(1318874398806).valueOf(); moment(1318874398806).unix(); moment([2000]).isLeapYear(); moment().zone(); @@ -191,12 +198,12 @@ moment.isMoment(moment()); moment.localeData('fr'); moment(1316116057189).fromNow(); -moment.localeData('en'); +moment.localeData('en'); var globalLang = moment(); var localLang = moment(); -localLang.localeData('fr'); -localLang.format('LLLL'); -globalLang.format('LLLL'); +localLang.localeData('fr'); +localLang.format('LLLL'); +globalLang.format('LLLL'); moment.duration(100); moment.duration(2, 'seconds'); @@ -223,8 +230,13 @@ adur.subtract(bdur).days(); adur.subtract(1).days(); adur.subtract(1, 'd').days(); -// Defining a custom language: -moment.localeData('en', { +// Selecting a language +moment.locale(); +moment.locale('en'); +moment.locale(['en', 'fr']); + +// Defining a custom language: +moment.locale('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], weekdays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], @@ -282,14 +294,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { months : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }); -moment.localeData('en', { +moment.locale('en', { months : function (momentToFormat: Moment, format: string) { // momentToFormat is the moment currently being formatted // format is the formatting string @@ -301,14 +313,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { monthsShort : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); -moment.localeData('en', { +moment.locale('en', { monthsShort : function (momentToFormat: Moment, format: string) { if (/^MMMM/.test(format)) { return this.nominative[momentToFormat.month()]; @@ -318,39 +330,39 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { weekdays : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] }); -moment.localeData('en', { +moment.locale('en', { weekdays : function (momentToFormat: Moment) { return this.weekdays[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : function (momentToFormat: Moment) { return this.weekdaysShort[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : function (momentToFormat: Moment) { return this.weekdaysMin[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -364,7 +376,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -374,7 +386,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { relativeTime : { future: "in %s", past: "%s ago", @@ -392,7 +404,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { meridiem : function (hour, minute, isLowercase) { if (hour < 9) { return "早上"; @@ -408,7 +420,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { calendar : { lastDay : '[Yesterday at] LT', sameDay : '[Today at] LT', @@ -421,7 +433,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { ordinal : function (number) { var b = number % 10; var output = (~~ (number % 100 / 10) === 1) ? 'th' : diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 2a8941d8f..ab629921d 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -16,7 +16,7 @@ var now = moment(); var day7 = moment([2010, 1, 14, 15, 25, 50, 125]); var day8 = moment([2010]); var day9 = moment([2010, 6]); -var day10 = moment([2010, 6, 10]); +var day10 = moment([2010, 6, 10]); var array = [2010, 1, 14, 15, 25, 50, 125]; var day11 = moment(Date.UTC.apply({}, array)); var day12 = moment.unix(1318781876); @@ -60,8 +60,8 @@ a.hours(); a.local(); a.hours(); -moment("2011-10-10", "YYYY-MM-DD").isValid(); -moment("2011-10-50", "YYYY-MM-DD").isValid(); +moment("2011-10-10", "YYYY-MM-DD").isValid(); +moment("2011-10-50", "YYYY-MM-DD").isValid(); moment("2011-10-10T10:20:90").isValid(); moment([2011, 0, 1]).isValid(); moment([2011, 0, 50]).isValid(); @@ -72,16 +72,16 @@ moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).sec moment().add('days', 7); moment().add('days', 7).add('months', 1); moment().add({days:7,months:1}); -moment().add('milliseconds', 1000000); +moment().add('milliseconds', 1000000); moment().add('days', 360); -moment([2010, 0, 31]); +moment([2010, 0, 31]); moment([2010, 0, 31]).add('months', 1); var m = moment(new Date(2011, 2, 12, 5, 0, 0)); -m.hours(); +m.hours(); m.add('days', 1).hours(); -var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); +var m2 = moment(new Date(2011, 2, 12, 5, 0, 0)); m2.hours(); -m2.add('hours', 24).hours(); +m2.add('hours', 24).hours(); var duration = moment.duration({'days': 1}); moment([2012, 0, 31]).add(duration); @@ -97,14 +97,14 @@ moment().subtract('days', 7); moment().seconds(30); moment().minutes(30); -moment().hours(12); +moment().hours(12); moment().date(5); moment().day(5); moment().day("Sunday"); moment().month(5); moment().month("January"); moment().year(1984); -moment().startOf('year'); +moment().startOf('year'); moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0); moment().startOf('hour'); moment().minutes(0).seconds(0).milliseconds(0); @@ -125,10 +125,10 @@ moment().isoWeek(45); moment().isoWeeks(); moment().isoWeeks(45); -var getMilliseconds: number = moment().milliseconds(); -var getSeconds: number = moment().seconds(); -var getMinutes: number = moment().minutes(); -var getHours: number = moment().hours(); +var getMilliseconds: number = moment().milliseconds(); +var getSeconds: number = moment().seconds(); +var getMinutes: number = moment().minutes(); +var getHours: number = moment().hours(); var getDate: number = moment().date(); var getDay: number = moment().day(); var getMonth: number = moment().month(); @@ -143,11 +143,11 @@ a3.utc(); a3.hours(); var a4 = moment([2010, 1, 14, 15, 25, 50, 125]); -a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); +a4.format("dddd, MMMM Do YYYY, h:mm:ss a"); a4.format("ddd, hA"); moment().format('\\L'); -moment().format('[today] DDDD'); +moment().format('[today] DDDD'); var a5 = moment([2007, 0, 29]); var b5 = moment([2007, 0, 28]); @@ -156,8 +156,8 @@ a5.from(b5); var a6 = moment([2007, 0, 29]); var b6 = moment([2007, 0, 28]); a6.from(b6); -a6.from([2007, 0, 28]); -a6.from(new Date(2007, 0, 28)); +a6.from([2007, 0, 28]); +a6.from(new Date(2007, 0, 28)); a6.from("1-28-2007"); var a7 = moment(); @@ -166,23 +166,23 @@ a7.from(b7); var start = moment([2007, 0, 5]); var end = moment([2007, 0, 10]); -start.from(end); +start.from(end); start.from(end, true); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(); -moment([2007, 0, 29]).fromNow(true); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(); +moment([2007, 0, 29]).fromNow(true); var a8 = moment([2007, 0, 29]); var b8 = moment([2007, 0, 28]); a8.diff(b8) ; a8.diff(b8, 'days'); -a8.diff(b8, 'years') +a8.diff(b8, 'years') a8.diff(b8, 'years', true); moment([2007, 0, 29]).toDate(); moment([2007, 1, 23]).toISOString(); -moment(1318874398806).valueOf(); +moment(1318874398806).valueOf(); moment(1318874398806).unix(); moment([2000]).isLeapYear(); moment().zone(); @@ -196,12 +196,12 @@ moment.isMoment(moment()); moment.localeData('fr'); moment(1316116057189).fromNow(); -moment.localeData('en'); +moment.localeData('en'); var globalLang = moment(); var localLang = moment(); -localLang.localeData('fr'); -localLang.format('LLLL'); -globalLang.format('LLLL'); +localLang.localeData('fr'); +localLang.format('LLLL'); +globalLang.format('LLLL'); moment.duration(100); moment.duration(2, 'seconds'); @@ -228,8 +228,13 @@ adur.subtract(bdur).days(); adur.subtract(1).days(); adur.subtract(1, 'd').days(); -// Defining a custom language: -moment.localeData('en', { +// Selecting a language +moment.locale(); +moment.locale('en'); +moment.locale(['en', 'fr']); + +// Defining a custom language: +moment.locale('en', { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], weekdays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], @@ -287,14 +292,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { months : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }); -moment.localeData('en', { +moment.locale('en', { months : function (momentToFormat: Moment, format: string) { // momentToFormat is the moment currently being formatted // format is the formatting string @@ -306,14 +311,14 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { monthsShort : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); -moment.localeData('en', { +moment.locale('en', { monthsShort : function (momentToFormat: Moment, format: string) { if (/^MMMM/.test(format)) { return this.nominative[momentToFormat.month()]; @@ -323,39 +328,39 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { weekdays : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] }); -moment.localeData('en', { +moment.locale('en', { weekdays : function (momentToFormat: Moment) { return this.weekdays[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysShort : function (momentToFormat: Moment) { return this.weekdaysShort[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] }); -moment.localeData('en', { +moment.locale('en', { weekdaysMin : function (momentToFormat: Moment) { return this.weekdaysMin[momentToFormat.day()]; } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -369,7 +374,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { longDateFormat : { LT: "h:mm A", L: "MM/DD/YYYY", @@ -379,7 +384,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { relativeTime : { future: "in %s", past: "%s ago", @@ -397,7 +402,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { meridiem : function (hour, minute, isLowercase) { if (hour < 9) { return "早上"; @@ -413,7 +418,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { calendar : { lastDay : '[Yesterday at] LT', sameDay : '[Today at] LT', @@ -426,7 +431,7 @@ moment.localeData('en', { } }); -moment.localeData('en', { +moment.locale('en', { ordinal : function (number) { var b = number % 10; var output = (~~ (number % 100 / 10) === 1) ? 'th' : diff --git a/moment/moment.d.ts b/moment/moment.d.ts index 57d967f78..6037b0ef0 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -382,8 +382,11 @@ interface MomentStatic { lang(language?: string): string; lang(language?: string, definition?: MomentLanguage): string; - localeData(language?: string): string; - localeData(language?: string, definition?: MomentLanguage): string; + locale(language?: string): string; + locale(language?: string[]): string; + locale(language?: string, definition?: MomentLanguage): string; + + localeData(language?: string): MomentLanguage; longDateFormat: any; relativeTime: any; diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 05f71d20a..83724c318 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -178,7 +178,7 @@ declare module "mongodb" { // Current definition by documentation version 1.3.13 (28.08.2013) export interface DbCreateOptions { // the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = ‘majority’ or tag acknowledges the write. - w?: string; + w?: any; // set the timeout for waiting for write concern to finish (combines with w option). wtimeout?: number; @@ -272,11 +272,11 @@ declare module "mongodb" { update(selector: Object, document: any, options: { safe?: boolean; upsert?: any; multi?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; distinct(key: string, query: Object, callback: (err: Error, result: any) => void): void; - distinct(key: string, query: Object, options: { readPreferences: string; }, callback: (err: Error, result: any) => void): void; + distinct(key: string, query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; count(callback: (err: Error, result: any) => void): void; count(query: Object, callback: (err: Error, result: any) => void): void; - count(query: Object, options: { readPreferences: string; }, callback: (err: Error, result: any) => void): void; + count(query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; drop(callback?: (err: Error, result: any) => void): void; @@ -429,7 +429,7 @@ declare module "mongodb" { showDiskLoc?: boolean; comment?: String; raw?: boolean; - readPreferences?: String; + readPreference?: String; partial?: boolean; } @@ -438,6 +438,6 @@ declare module "mongodb" { serializeFunctions?: any; raw?: boolean; pkFactory?: any; - readPreferences?: string; + readPreference?: string; } } diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index e9057abc7..abfd5625e 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -153,7 +153,7 @@ declare module "mongoose" { findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; diff --git a/mustache/mustache-0.7.3-tests.ts b/mustache/mustache-0.7.3-tests.ts new file mode 100644 index 000000000..f95913cc7 --- /dev/null +++ b/mustache/mustache-0.7.3-tests.ts @@ -0,0 +1,11 @@ +/// + +var view = { title: "Joe", calc: function () { return 2 + 4; } }; +var output = Mustache.render("{{title}} spends {{calc}}", view); + +var person = { firstName: "John", lastName: "Smith", blogURL: "http://testblog.com" }; +var template = "

{{firstName}} {{lastName}}

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

{{firstName}} {{lastName}}

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

{{firstName}} {{lastName}}

Blog: {{blogURL}}"; +var html = Mustache.to_html(template3, view3); diff --git a/mustache/mustache-tests.ts.tscparams b/mustache/mustache-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/mustache/mustache-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/mustache/mustache.d.ts b/mustache/mustache.d.ts index 9cd5e6f69..3f0a83dfa 100644 --- a/mustache/mustache.d.ts +++ b/mustache/mustache.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Mustache 0.7 +// Type definitions for Mustache 0.8.2 // Project: https://github.com/janl/mustache.js -// Definitions by: Boris Yankov +// Definitions by: Mark Ashley Bell // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -15,21 +15,20 @@ interface MustacheScanner { } interface MustacheContext { - view; - parent; + view: any; + parentContext: MustacheContext; - clearCache(); - push(view): MustacheContext; + push(view: any): MustacheContext; lookup(name: string): any; } interface MustacheWriter { (view: any): string; - clearCache(); - compile(template: string, tags); - compilePartial(name, template, tags); - compileTokens(tokens, template); - render(template, view, partials); + + clearCache(): void; + parse(template: string, tags?: any): any; + render(template: string, view: any, partials: any): string; + renderTokens(tokens: string[], context: MustacheContext, partials: any, originalTemplate: any): string; } interface MustacheStatic { @@ -39,16 +38,12 @@ interface MustacheStatic { Scanner: MustacheScanner; Context: MustacheContext; Writer: MustacheWriter; - escape; + escape: any; - parse(template: string, tags); clearCache(): MustacheWriter; - compile(template: string): MustacheWriter; - compile(template: string, tags): MustacheWriter; - compilePartial(name: string, template: string, tags): MustacheWriter; - compileTokens(tokens, template: string): MustacheWriter; + parse(template: string, tags?: any): any; render(template: string, view: any, partials?: any): string; - to_html(template: string, view: any, partials?: any, send?): string; + to_html(template: string, view: any, partials?: any, send?: any): any; } declare var Mustache: MustacheStatic; diff --git a/mustache/mustache.d.ts.tscparams b/mustache/mustache.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/mustache/mustache.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index 95ff46c25..cb759f19e 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -1,6 +1,8 @@ -// Type definitions for Azure SDK for Node - v0.6.10 +// Type definitions for Azure SDK for Node - v0.9.16 // Project: https://github.com/WindowsAzure/azure-sdk-for-node -// Definitions by: Andrew Gaspar , Anti Veeranna +// Definitions by: Andrew Gaspar , +// Anti Veeranna , +// Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -10,6 +12,8 @@ */ declare module "azure" { import events = require("events"); + import stream = require("stream"); + import url = require("url"); //#region Services export class TableService extends BatchServiceClient { @@ -18,6 +22,8 @@ declare module "azure" { static incorrectTableQuery: string; static incorrectPartitionErr: string; + //#region Constructors + /** * Creates a new TableService object. * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. @@ -48,29 +54,42 @@ declare module "azure" { */ constructor(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string); - getServiceProperties(callback?: (error: any, servicePropertiesResult: any, response: any) => void ): void; - getServiceProperties(options: TimeoutIntervalOptions, callback?: (error: any, servicePropertiesResult: any, response: any) => void ): void; + //#endregion - setServiceProperties(serviceProperties: any, options: TimeoutIntervalOptions, callback?: Function): void; + //#region Service Methods - getTable(table: string, callback?: TableRequestCallback ): void; - getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback ): void; + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; - createTable(table: string, callback?: TableRequestCallback ): void; - createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback ): void; + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback ): void; + //#endregion + + //#region Table Methods + + getTable(table: string, callback?: TableRequestCallback): void; + getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; + + createTable(table: string, callback?: TableRequestCallback): void; + createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; + + createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback): void; createTableIfNotExists(table: string, options: TimeoutIntervalOptions, callback?: CreateTableIfNotExistsCallback): void; - deleteTable(table: string, callback?: DeleteTableCallback ): void; - deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback ): void; + deleteTable(table: string, callback?: DeleteTableCallback): void; + deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback): void; - queryTables(callback?: QueryTablesCallback ): void; - queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback ): void; + queryTables(callback?: QueryTablesCallback): void; + queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback): void; + + //#endregion + + //#region Entities Methods + + queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback): void; + queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback): void; - queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback ): void; - queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback ): void; - queryEntities(tableQuery: TableQuery, callback?: QueryEntitiesCallback): void; queryEntities(tableQuery: TableQuery, options: TimeoutIntervalOptions, callback?: QueryEntitiesCallback): void; @@ -91,14 +110,513 @@ declare module "azure" { deleteEntity(tableName: string, entityDescriptor: Entity, callback?: DeleteEntityCallback): void; deleteEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: DeleteEntityCallback): void; + + //#endregion } - export class BlobService { + export class BlobService extends StorageServiceClient { + singleBlobPutThresholdInBytes: number; + parallelOperationThreadCount: number; + SpeedSummary: typeof SpeedSummary; + + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account’s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account’s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Containers Methods + + /** + * Lists a segment containing a collection of container items under the specified account. + */ + listContainers(callback: ListContainersCallback): void; + listContainers(options: ListContainersOptions, callback: ListContainersCallback): void; + + /** + * Creates a new container under the specified account. + * If a container with the same name already exists, the operation fails. + */ + createContainer(container: string, callback: StorageCallback): void; + createContainer(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Creates a new container under the specified account if the container does not exists. + */ + createContainerIfNotExists(container: string, callback: StorageCallback): void; + createContainerIfNotExists(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Retrieves a container and its properties from a specified account. + */ + getContainerProperties(container: string, callback: StorageCallback): void; + getContainerProperties(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Returns all user-defined metadata for the container. + */ + getContainerMetadata(container: string, callback: StorageCallback): void; + getContainerMetadata(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets the container's metadata. + */ + setContainerMetadata(container: string, metadata: StorageMetadata, callback: StorageCallback): void; + setContainerMetadata(container: string, metadata: StorageMetadata, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Gets the container's ACL. + */ + getContainerAcl(container: string, callback: StorageCallback): void; + getContainerAcl(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Updates the container's ACL. + */ + setContainerAcl(container: string, publicAccessLevel: string, callback: StorageCallback): void; + setContainerAcl(container: string, publicAccessLevel: string, options: StorageAclOptions, callback: StorageCallback): void; + + /** + * Marks the specified container for deletion. + * The container and any blobs contained within it are later deleted during garbage collection. + */ + deleteContainer(container: string, callback: StorageCallbackVoid): void; + deleteContainer(container: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Blob Methods + + /** + * Lists all of the blobs in the given container. + */ + listBlobs(container: string, callback: ListBlobsCallback): void; + listBlobs(container: string, options: ListBlobsOptions, callback: ListBlobsCallback): void; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. + * It does not return or modify the content of the blob. + */ + getBlobProperties(container: string, blob: string, callback: StorageCallback): void; + getBlobProperties(container: string, blob: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined properties for the specified blob or snapshot. + * It does not return or modify the content of the blob. + */ + setBlobProperties(container: string, blob: string, callback: StorageCallback): void; + setBlobProperties(container: string, blob: string, options: SetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs + * It does not return or modify the content of the blob. + */ + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, callback: StorageCallback): void; + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Provides a stream to read from a blob. + */ + getBlob(container: string, blob: string, callback: StorageCallback): stream.Readable; + getBlob(container: string, blob: string, options: ReadBlobOptions, callback: StorageCallback): stream.Readable; + + /** + * Downloads a blob into a file. + */ + getBlobToFile(container: string, blob: string, localFileName: string, callback: StorageCallback): void; + getBlobToFile(container: string, blob: string, localFileName: string, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a stream. + */ + getBlobToStream(container: string, blob: string, stream: stream.Writable, callback: StorageCallback): void; + getBlobToStream(container: string, blob: string, stream: stream.Writable, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a text string. + */ + getBlobToText(container: string, blob: string, callback: GetBlobToTextCallback): void; + getBlobToText(container: string, blob: string, options: ReadBlobOptions, callback: GetBlobToTextCallback): void; + + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + */ + deleteBlob(container: string, blob: string, callback: StorageCallback): void; + deleteBlob(container: string, blob: string, options: DeleteBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + createBlobSnapshot(container: string, blob: string, callback: StorageCallback): void; + createBlobSnapshot(container: string, blob: string, options: BlobSnapshotOptions, callback: StorageCallback): void; + + /** + * Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. + */ + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, callback: StorageCallback): void; + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, options: CopyBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + abortCopyBlob(container: string, blob: string, copyId: string, callback: StorageCallbackVoid): void; + abortCopyBlob(container: string, blob: string, copyId: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + /** + * Retrieves a shared access signature token. + */ + generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): SharedAccessSignatureResult; + + /** + * Retrieves a blob or container URL. + */ + getBlobUrl(container: string): string; + getBlobUrl(container: string, blob: string): string; + getBlobUrl(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Uploads a blob. + */ + createBlob(container: string, blob: string, blobType: string, callback: StorageCallback): stream.Writable; + createBlob(container: string, blob: string, blobType: string, options: UploadBlockBlobOptions, callback: StorageCallback): stream.Writable; + + //#endregion + + //#region Page Blob Methods + + /** + * Creates a page blob of the specified length. + */ + createPageBlob(container: string, blob: string, length: number, callback: StorageCallbackVoid): void; + createPageBlob(container: string, blob: string, length: number, options: SetBlobPropertiesOptions, callback: StorageCallbackVoid): void; + + /** + * Updates a page blob from a stream. + */ + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Updates a page blob from a text string. + */ + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Lists page ranges. + * Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + */ + listBlobRegions(container: string, blob: string, callback: StorageCallback): void; + listBlobRegions(container: string, blob: string, options: PageRangeOptions, callback: StorageCallback): void; + + /** + * Clears a range of pages. + */ + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, callback: StorageCallbackVoid): void; + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, options: LeaseAccessConditionsOptions, callback: StorageCallbackVoid): void; + + /** + * Resizes a page blob. + */ + resizePageBlob(container: string, blob: string, size: number, callback: StorageCallback): void; + resizePageBlob(container: string, blob: string, size: number, options: LeaseAccessConditionsOptions, callback: StorageCallback): void; + + /** + * Sets the page blob's sequence number. + */ + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, callback: StorageCallback): void; + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + //#endregion + + //#region Block Blob Methods + + /** + * Uploads a block blob from file. + */ + putBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + putBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a stream. + */ + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a text string. + */ + createBlockBlobFromText(container: string, blob: string, text: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromText(container: string, blob: string, text: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, callback: StorageCallbackVoid): void; + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, callback: StorageCallbackVoid): void; + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written to the server in a prior + * createBlock operation. + */ + commitBlobBlocks(container: string, blob: string, blockList: BlockList, callback: StorageCallback): void; + commitBlobBlocks(container: string, blob: string, blockList: BlockList, options: CreateBlockOptions, callback: StorageCallback): void; + + /** + * Retrieves the list of blocks that have been uploaded as part of a block blob. + */ + listBlobBlocks(container: string, blob: string, blockListType: string, callback: StorageCallback): void; + listBlobBlocks(container: string, blob: string, blockListType: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Generate a random block id prefix. + */ + generateBlockIdPrefix(): string; + /** + * Get a block id according to prefix and block number. + */ + getBlockId(prefix: string, number: number): string; + + //#endregion + + //#region Lease Methods + + /** + * Acquires a new lease. + * If container and blob are specified, acquires a blob lease. + * Otherwise, if only container is specified and blob is null, acquires a container lease. + */ + acquireLease(container: string, blob: string, callback: StorageCallback): void; + acquireLease(container: string, blob: string, options: LeaseOptions, callback: StorageCallback): void; + + /** + * Renews an existing lease. + * If container and blob are specified, renews the blob lease. + * Otherwise, if only container is specified and blob is null, renews the container lease. + */ + renewLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + renewLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Releases the lease. + * If container and blob are specified, releases the blob lease. + * Otherwise, if only container is specified and blob is null, releases the container lease. + */ + releaseLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + releaseLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. + * If container and blob are specified, breaks the blob lease. + * Otherwise, if only container is specified and blob is null, breaks the container lease. + */ + breakLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + breakLease(container: string, blob: string, leaseId: string, options: BreakLeaseOptions, callback: StorageCallback): void; + + //#endregion } - export class QueueService { + export class QueueService extends StorageServiceClient { + authenticationProvider: SharedKey; + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account’s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account’s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Queue Methods + + /** + * Lists all queues under the given account. + */ + listQueues(callback: ListQueuesCallback): void; + listQueues(options: ListQueuesOptions, callback: ListQueuesCallback): void; + + /** + * Creates a new queue under the given account. + */ + createQueue(queue: string, callback: StorageCallback): void; + createQueue(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Creates a new queue under the given account if it doesn't exist. + */ + createQueueIfNotExists(queue: string, callback: StorageCallback): void; + createQueueIfNotExists(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Permanently deletes the specified queue. + */ + deleteQueue(queue: string, callback: StorageCallback): void; + deleteQueue(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Returns queue properties, including user-defined metadata. + */ + getQueueMetadata(queue: string, callback: StorageCallback): void; + getQueueMetadata(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. + */ + setQueueMetadata(queue: string, metadata: StorageMetadata, callback: StorageCallback): void; + setQueueMetadata(queue: string, metadata: StorageMetadata, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + //#endregion + + //#region Message Methods + + /** + * Adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message + * invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request + * with UTF-8 encoding. The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size + * for previous versions. + */ + createMessage(queue: string, messageText: string, callback: StorageCallback): void + createMessage(queue: string, messageText: string, options: CreateQueueMessageOptions, callback: StorageCallback): void + + /** + * Retrieves a message from the queue and makes it invisible to other consumers. + */ + getMessages(queue: string, callback: StorageCallback): void; + getMessages(queue: string, options: GetQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Retrieves a message from the front of the queue, without changing the message visibility. + */ + peekMessages(queue: string, callback: StorageCallback): void; + peekMessages(queue: string, options: PeekQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Deletes a specified message from the queue. + */ + deleteMessage(queue: string, messageId: string, popreceipt: string, callback: StorageCallback): void + deleteMessage(queue: string, messageId: string, popreceipt: string, options: TimeoutIntervalOptions, callback: StorageCallback): void + + /** + * Clears all messages from the queue. + */ + clearMessages(queue: string, callback: StorageCallbackVoid): void; + clearMessages(queue: string, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + /** + * Deletes a specified message from the queue. + */ + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, callback: StorageCallback): void + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, options: UpdateQueueMessagesOptions, callback: StorageCallback): void + + //#endregion } export class ServiceBusService { @@ -116,6 +634,7 @@ declare module "azure" { export class SqlManagementService { } //#endregion + //#region Service Creators export function createTableService(): TableService; export function createTableService(connectionString: string): TableService; @@ -140,25 +659,122 @@ declare module "azure" { export function createSqlManagementService(subscriptionId: string, authentication: string, hostOptions: string): SqlManagementService; //#endregion + //#region RoleEnvironment + interface RoleEnvironmentInterface extends events.EventEmitter { - getCurrentRoleInstance(callback: (error: any, instance: any) => void): void; - getDeploymentId(callback: (error: any, id:string) => void): void; - isAvailable(callback: (error: any, available: boolean) => void): void; - isEmulated(callback: (error: any, emulated: boolean) => void): void; - getRoles(callback: (error: any, roles: any) => void): void; - getConfigurationSettings(callback: (error: any, settings: any) => void): void; - getLocalResources(callback: (error: any, resources: any) => void): void; - requestRecycle(callback: (error: any) => void): void; - setStatus(roleInstanceStatus: any, expirationUtc: any, callback: (error: any) => void): void; - clearStatus(callback: (error: any) => void): void; + incorrectCallbackErr: string; + clientId: string; + VersionEndpointFixedPath: string; + EnvironmentVariables: { + [key: string]: string; + VersionEndpointEnvironmentName: string; + }; + + /** + * Returns a RoleInstance object that represents the role instance + * in which this code is currently executing. + */ + getCurrentRoleInstance(callback: SimpleCallback): void; + + /** + * Returns the deployment ID that uniquely identifies the deployment in + * which this role instance is running. + */ + getDeploymentId(callback: SimpleCallback): void; + + /** + * Indicates whether the role instance is running in the Microsoft Azure + * environment. It is good practice to enclose any code that uses + * service runtime in the isAvailable callback. + */ + isAvailable(callback: SimpleCallback): void; + + /** + * Indicates whether the role instance is running in the development fabric. + */ + isEmulated(callback: SimpleCallback): void; + + /** + * Returns the set of Role objects defined for your service. + * Roles are defined in the service definition file. + */ + getRoles(callback: SimpleCallback>): void; + + /** + * Retrieves the settings in the service configuration file. + * + * A role's configuration settings are defined in the service definition file. + * Values for configuration settings are set in the service configuration file. + * For more information on configuration settings, see the [Service Definition Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758711.aspx) + * and [Service Configuration Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758710.aspx). + */ + getConfigurationSettings(callback: SimpleCallback>): void; + + /** + * Retrieves the set of named local storage resources, along with the path. + * For example, the DiagnosticStore resource which is defined for every role + * provides a location for runtime diagnostics and logs. + */ + getLocalResources(callback: SimpleCallback>): void; + + /** + * Requests that the current role instance be stopped and restarted. + * + * Before the role instance is recycled, the Microsoft Azure load balancer takes the role instance out of rotation. + * This ensures that no new requests are routed to the instance while it is restarting. + * + * A call to `RequestRecycle` initiates the normal shutdown cycle. Microsoft Azure raises the + * `Stopping` event and calls the `OnStop` method so that you can run the necessary code to + * prepare the instance to be recycled. + */ + requestRecycle(callback: ErrorCallback): void; + + /** + * Sets the status of the role instance. + * + * An instance may indicate that it is in one of two states: Ready or Busy. If an instance's state is Ready, it is + * prepared to receive requests from the load balancer. If the instance's state is Busy, it will not receive + * requests from the load balancer. + */ + setStatus(roleInstanceStatus: string, expirationUtc: Date, callback: ErrorCallback): void; + + /** + * Clears the status of the role instance. + * An instance may indicate that it has completed communicating status by calling this method. + */ + clearStatus(callback: ErrorCallback): void; } export var RoleEnvironment: RoleEnvironmentInterface; - + + //#endregion //#region Export of internal classes export class WebResource { + rawResponse: boolean; + queryString: Dictionary; + constructor(); + + get(path: string): WebResource; + put(path: string): WebResource; + post(path: string): WebResource; + merge(path: string): WebResource; + head(path: string): WebResource; + del(path: string): WebResource; + + withProperty(name: string, value: string): WebResource; + withRawResponse(rawResponse: boolean): WebResource; + withHeadersOnly(headersOnly: boolean): WebResource; + withQueryOption(name: string, value: string, defaultValue: string): WebResource; + withQueryOptions(queryOptions: Dictionary): WebResource; + withHeader(name: string, value: string): WebResource; + withHeaders(headers: Dictionary): WebResource; + withBody(body: any): WebResource; + addOptionalMetadataHeaders(metadata: StorageMetadata): WebResource; + + validResponse(statusCode: number): boolean; + pipeInput(inputStream: stream.Stream, destStream: stream.Stream): stream.Stream; } export class ServiceClient extends events.EventEmitter { @@ -185,12 +801,27 @@ declare module "azure" { performRequest(webResource: WebResource, outputData: string, options: any, callback: Function): void; performRequestOutputStream(webResource: WebResource, outputStream: any, options: any, callback: Function): void; performRequestInputStream(webResource: WebResource, outputData: string, inputStream: any, options: any, callback: Function): void; - withFilter(newFilter: { handle: (requestOptions: any, next: Function) => void; }): ServiceClient; + withFilter(newFilter: Filter): ServiceClient; parseMetadataHeaders(headers: any): any; isEmulated(): boolean; setProxy(proxyUrl: string, proxyPort: number): void; } + export class BatchServiceClient extends StorageServiceClient { + operations: any[]; + + constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); + beginBatch(): void; + isInBatch(): boolean; + rollback(): void; + hasOperations(): boolean; + addOperation(webResource: WebResource, outputData: any): void; + commitBatch(callback: (error: any, operationResponses: any[], response: any) => void): void; + commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void): void; + processResponse(responseObject: any, requestOperations: any[]): any[]; + processOperation(webResource: WebResource, rawResponse: string): any; + } + export class ServiceManagementClient { } @@ -208,77 +839,531 @@ declare module "azure" { toPath(): string; } - export class BatchServiceClient extends StorageServiceClient { - operations: any[]; + export class BlobResult { + blob: string; + container: string; - constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); - beginBatch(): void; - isInBatch(): boolean; - rollback(): void; - hasOperations(): boolean; - addOperation(webResource: WebResource, outputData: any): void; - commitBatch(callback: (error: any, operationResponses: any[], response: any) => void ): void; - commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void ): void; - processResponse(responseObject: any, requestOperations: any[]): any[]; - processOperation(webResource: WebResource, rawResponse: string): any; + etag: string; + lastModified: Date; + contentType: string; + contentEncoding: string; + contentLanguage: string; + contentMD5: string; + cacheControl: string; + contentRange: string; + contentTypeHeader: string; + contentEncodingHeader: string; + contentLanguageHeader: string; + contentMD5Header: string; + cacheControlHeader: string; + contentLength: number; + contentLengthHeader: number; + contentDisposition: string; + contentDispositionHeader: string; + range: string; + rangeHeader: string; + getContentMd5: string; + acceptRanges: string; + blobType: string; + leaseStatus: string; + leaseId: string; + leaseDuration: string; + leaseState: string; + sequenceNumber: string; + copyStatus: string; + copyCompletionTime: string; + copyStatusDescription: string; + copyId: string; + copyProgress: number; + requestId: string; + + metadata: StorageMetadata; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + + static parse(blobXml: any): BlobResult; + static setHeadersFromBlob(webResource: WebResource, blob: BlobResult): void; + + getPropertiesFromHeaders(headers: any): void; + } + + export class ContainerResult { + name: string; + publicAccessLevel: string; + + etag: string; + lastModified: Date; + leaseStatus: string; + leaseDuration: string; + leaseState: string; + requestId: string; + + metadata: StorageMetadata; + signedIdentifiers: SignedIdentifier[]; + + constructor(); + constructor(name: string); + constructor(name: string, publicAccessLevel: string); + + static parse(containerXml: any): ContainerResult; + + getPropertiesFromHeaders(headers: any): void; + } + + export class LeaseResult { + container: string; + blob: string; + id: string; + time: Date; + etag: string; + lastModified: Date; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + constructor(container: string, blob: string, id: string); + constructor(container: string, blob: string, id: string, time: Date); + + getPropertiesFromHeaders(header: any): void; + } + + export class QueueResult { + name: string; + metadata: StorageMetadata; + approximatemessagecount: number; + + constructor(); + constructor(name: string); + constructor(name: string, metadata: StorageMetadata); + + static parse(messageXml: any): QueueResult; + + getPropertiesFromHeaders(headers: any): void; + } + + export class QueueMessageResult { + queue: string; + messageid: string; + popreceipt: string; + metadata: StorageMetadata; + + constructor(); + constructor(queue: string); + constructor(queue: string, messageid: string); + constructor(queue: string, messageid: string, popreceipt: string); + constructor(queue: string, messageid: string, popreceipt: string, metadata: StorageMetadata); + + static serialize(messageJs: string): string; + static parse(messageXml: any): QueueMessageResult; + + getPropertiesFromHeaders(headers: any): void; + } + + export class SpeedSummary { + name: string; + totalSize: number; + completeSize: number; + + _startTime: Date; + _timeWindowInSeconds: number; + _timeWindow: number; + _totalWindowSize: number; + _speedTracks: number[]; + _speedTrackPtr: number; + + constructor(name: string); + + /** + * Get running seconds + */ + getElapsedSeconds(): string; + getElapsedSeconds(humanReadable: boolean): number; + + /** + * Get complete percentage + */ + getCompletePercent(): number; + getCompletePercent(len: number): number; + + /** + * Get average upload/download speed + */ + getAverageSpeed(): string; + getAverageSpeed(humanReadable: boolean): number; + + /** + * Get internal speed + */ + getSpeed(): string; + getSpeed(humanReadable: boolean): number; + + /** + * Get auto increment function + */ + getSpeed(size: number): (error: Error, value: any) => void; + + /** + * Get total size + */ + getTotalSize(): string; + getTotalSize(humanReadable: boolean): number; + + /** + * Get completed data size + */ + getCompleteSize(): string; + getCompleteSize(humanReadable: boolean): number; } export module Constants { } - export class LinearRetryPolicyFilter { + export interface Filter { + handle(requestOptions: any, next: Function): void; + } + + export class LinearRetryPolicyFilter implements Filter { constructor(retryCount?: number, retryInterval?: number); retryCount: number; retryInterval: number; + handle(requestOptions: any, next: Function): void; } - export class ExponentialRetryPolicyFilter { + export class ExponentialRetryPolicyFilter implements Filter { constructor(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number); retryCount: number; retryInterval: number; minRetryInterval: number; maxRetryInterval: number; + handle(requestOptions: any, next: Function): void; + } + + export class HmacSha256Sign { + } export class SharedAccessSignature { + storageAccount: string; + storageAccessKey: string; + permissionSet: string[]; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, permissionSet: string[]) + + /** + * Generates the query string for a shared access signature signing. + */ + generateSignedQueryString(path: string, queryString: Dictionary, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): Dictionary; + + /** + * Signs a request with the signature header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Generates the shared access signature for a resource. + */ + _generateSignature(path: string, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Generates the query string for a shared access signature signing. + */ + _permissionMatchesRequest(sharedAccessSignature: string, webResource: WebResource, resourceType: string, requiredPermissions: string[]): string; } export class SharedKey { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; } export class SharedKeyLite { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; } export class SharedKeyTable { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; } export class SharedKeyLiteTable { + torageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; } export module ISO8061Date { + /** + * Formats a date into an iso 8061 string. + */ + export function format(date: Date): string; + /** + * Parses an ISO 8061 date string into a date object. + */ + export function parse(stringDateTime: string): Date; } export class Logger { + level: string; + loggerFunction: (level: string, message: string) => void; + static LogLevels: { + EMERGENCY: string; + ALERT: string; + CRITICAL: string; + ERROR: string; + WARNING: string; + NOTICE: string; + INFO: string; + DEBUG: string; + }; + static logPriority: string[]; + + log(level: string, message: string): void; + emergency(message: string): void; + alert(message: string): void; + critical(message: string): void; + error(message: string): void; + warning(message: string): void; + notice(message: string): void; + info(message: string): void; + debug(message: string): void; + + defaultLoggerFunction(level: string, message: string): void; } export class ConnectionStringParser { + _value: string; + _pos: number; + _state: string; + constructor(connectionString: string); + + _parse(options: ConnectionStringParseOptions): Dictionary; + + _extractKey(): string; + _extractString(quote: string): string; + _extractValue(): string; + + _skipWhitespaces(): void; + _skipOperator(operator: string): void; + + static parse(connectionString: string): Dictionary; } export module ServiceSettings { + export var DEFAULT_PROTOCOL: string; + export class NoMatchError implements Error { + name: string; + message: string; + constr: any; + + constructor(); + constructor(message: string); + constructor(message: string, constr: any); + } + + /** + * Throws an exception if the connection string format does not match any of the + * available formats. + */ + export function noMatchConnectionString(connectionString: string): void; + + /** + * Throws an exception if the settings dont match any of the available formats. + */ + export function noMatchSettings(settings: any): void; + + /** + * Parses the connection string and then validate that the parsed keys belong to + * the validSettingKeys + */ + export function parseAndValidateKeys(connectionString: string, validKeys: string[]): string[]; + + /** + * Creates an anonymous function that acts as predicate to perform a validation. + */ + export function getValidator(requirements: Dictionary, isRequired: boolean, atLeastOne: boolean): ValidatorFunction; + + /** + * Creates a setting value condition that validates it is one of the passed valid values. + */ + export function setting(name: string): string[]; + + /** + * Creates an "at least one" predicate for the provided list of requirements. + */ + export function atLeastOne(...args: any[]): ValidatorFunction; + + /** + * Creates an optional predicate for the provided list of requirements. + */ + export function optional(...args: any[]): ValidatorFunction; + + /** + * Creates an required predicate for the provided list of requirements. + */ + export function allRequired(...args: any[]): ValidatorFunction; + + /** + * Creates a setting value condition using the passed predicate. + */ + export function settingWithFunc(name: string, predicate: Function): Requirement[]; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function matchedSpecification(settings: Dictionary): boolean; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function parseHost(uri: string): url.Url; } export class StorageServiceSettings { + _name: string; + _key: string; + _blobEndpointUri: string; + _queueEndpointUri: string; + _tableEndpointUri: string; + _usePathStyleUri: boolean; + constructor(name: string, key: string, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string, usePathStyleUri: boolean); + + /** + * Returns a StorageServiceSettings with development storage credentials using + * the specified proxy Uri. + */ + static _getDevelopmentStorageAccount(): StorageServiceSettings; + static _getDevelopmentStorageAccount(proxy: string): StorageServiceSettings; + + /** + * Gets a StorageServiceSettings object that references the development storage + * account. + */ + static getDevelopmentStorageAccountSettings(): StorageServiceSettings; + + /** + * Gets the default service endpoint using the specified protocol and account + * name. + */ + static _getDefaultServiceEndpoint(settings: Dictionary, dns: string): string; + + /** + * Creates StorageServiceSettings object given endpoints uri. + */ + static _createStorageServiceSettings(settings: Dictionary, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string): StorageServiceSettings; + + /** + * Creates a ServiceBusSettings object from a set of settings. + */ + static createFromSettings(settings: Dictionary): StorageServiceSettings; + + /** + * Creates a StorageServiceSettings object from the given connection string. + */ + static createFromConnectionString(connectionString: string): StorageServiceSettings; + + static createExplicitlyOrFromEnvironment(storageAccount: string, storageAccessKey: string, host: string): StorageServiceSettings; + + static isDevelopmentStorage(storageAccount: string, storageAccessKey: string, parsedHost: string): boolean; + + static createFromConfig(config: any): StorageServiceSettings; + + static customizeConfig(config: any): void; } export class ServiceBusSettings { @@ -290,11 +1375,87 @@ declare module "azure" { } export module Validate { + /** + * Checks if the given uri is valid or not. + */ + export function isValidUri(uri: string): boolean; + /** + * Validates that a clusterCreationObject is properly formed. + */ + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions): void; + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions, callback: ErrorCallback): void; + + export function isValidUuid(uuid: string): void; + export function isValidUuid(uuid: string, callback: ErrorCallback): void; + + /** + * Creates a anonymous function that check if a given key is base 64 encoded. + */ + export function isBase64Encoded(key: string): boolean; + + /** + * Validates a function. + */ + export function isValidFunction(functionObject: any, functionName: string): void; + + /** + * Validates that a Service Bus namespace name + * is legally allowable. Does not check availability. + */ + export function namespaceNameIsValid(name: string): boolean; + export function namespaceNameIsValid(name: string, callback: ErrorCallback): boolean; + + /** + * Validates a container name. + */ + export function containerNameIsValid(containerName: string): boolean; + export function containerNameIsValid(containerName: string, callback: ErrorCallback): boolean; + + /** + * Validates a blob name. + */ + export function blobNameIsValid(containerName: string, blob: string): boolean; + export function blobNameIsValid(containerName: string, blob: string, callback: ErrorCallback): boolean; + + /** + * Validates a table name. + */ + export function tableNameIsValid(tableName: string): boolean; + export function tableNameIsValid(tableName: string, callback: ErrorCallback): boolean; + + /** + * Validates a queue name. + */ + export function queueNameIsValid(queueName: string): boolean; + export function queueNameIsValid(queueName: string, callback: ErrorCallback): boolean; + + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number): boolean; + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback: ErrorCallback): boolean; + + export function validateArgs(functionName: string, validationRules: Function): boolean; } export module date { + /** + * Generates a Date object which is in the given days from now. + */ + export function daysFromNow(days: number): Date; + /** + * Generates a Date object which is in the given hours from now. + */ + export function hoursFromNow(hours: number): Date; + + /** + * Generates a Date object which is in the given minutes from now. + */ + export function minutesFromNow(minutes: number): Date; + + /** + * Generates a Date object which is in the given seconds from now. + */ + export function secondsFromNow(seconds: number): Date; } //#endregion @@ -302,28 +1463,104 @@ declare module "azure" { export interface WebResponse { isSuccessful: boolean; statusCode: number; - body: { - entry: { - id: string; - title: any; - updated: string; - author: { - name: any; - }; - link: any; - category: any; - content: any; - }; + body: { + entry: { + id: string; + title: any; + updated: string; + author: { + name: any; + }; + link: any; + category: any; + content: any; + }; }; headers: any; md5: any; } + //#region Common Interfaces + export interface SimpleCallback { + (error: Error, result: T): void; + } + export interface ErrorCallback { + (error: Error): void; + } + export interface StorageCallbackVoid { + (err: Error, response: WebResponse): void; + } + export interface StorageCallback { + (err: Error, result: T, response: WebResponse): void; + } + export interface StorageServiceStatsCallback extends StorageCallback { } + export interface StorageServicePropertiesCallback extends StorageCallback { } + export interface TimeoutIntervalOptions { + locationMode?: string; timeoutIntervalInMs?: number; + maximumExecutionTimeInMs?: number; + } + export interface MetadataOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; + } + export interface StorageAclOptions extends TimeoutIntervalOptions { + leaseId?: string; + signedIdentifiers: SignedIdentifier[] } - ///#region TableService Callbacks + export interface Dictionary { + [key: string]: T; + } + export interface StorageServiceProperties { + Logging: { + Version: number; + Delete: boolean; + Read: boolean; + Write: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + Metrics: { + Version: number; + Enabled: boolean; + IncludeAPIs: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + DefaultServiceVersion: string; + } + export interface StorageServiceStats { + GeoReplication: { + Status: string; + LastSyncTime: Date; + } + } + export interface SignedIdentifier { + Id: string; + AccessPolicy: SharedAccessPolicy; + } + export interface StorageMetadata { + [key: string]: string; + } + export interface ContinuationToken { + nextMarker: string; + targetLocation: string; + } + export interface SharedAccessPolicy { + Id?: string; + AccessPolicy: { + Start?: Date; + Expiry: Date; + Permission?: string; + } + } + //#endregion + //#region TableService Interfaces export interface TableRequestCallback { (error: Error, tableResult: { TableName: string; }, response: WebResponse): void; } @@ -387,13 +1624,245 @@ declare module "azure" { etag?: string; } //#endregion + //#region BlobService Interfaces + export interface LeaseIdOptions extends TimeoutIntervalOptions { + leaseId?: string; + } + export interface AccessConditionsOptions extends TimeoutIntervalOptions { + accessConditions?: StorageAccessCondition; + } + export interface LeaseAccessConditionsOptions extends LeaseIdOptions { + accessConditions?: StorageAccessCondition; + } + + export interface ListContainersOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; + } + export interface ListContainersCallback { + (err: Error, containers: ContainerResult[], continuationToken: ContinuationToken, response: WebResponse): void; + } + export interface CreateContainerOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; + publicAccessLevel?: string; + } + export interface GetContainerPropertiesOptions extends TimeoutIntervalOptions { + leaseId?: string; + } + export interface GetContainerMetadataOptions extends GetContainerPropertiesOptions { + accessConditions?: StorageAccessCondition; + } + + export interface ListBlobsOptions extends ListContainersOptions { + prefix?: string; + delimiter?: string; + } + export interface ListBlobsCallback { + (err: Error, blobs: BlobResult[], continuationToken: ContinuationToken, response: WebResponse): void; + } + export interface GetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + snapshotId?: string; + } + export interface SetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; + } + export interface ReadBlobOptions extends GetBlobPropertiesOptions { + rangeStart?: string; + rangeEnd?: string; + useTransactionalMD5?: boolean; + disableContentMD5Validation?: boolean; + } + export interface GetBlobToTextCallback { + (err: Error, text: string, result: BlobResult, response: WebResponse): void; + } + export interface DeleteBlobOptions extends GetBlobPropertiesOptions { + deleteSnapshots?: string; + } + export interface BlobSnapshotOptions extends GetBlobPropertiesOptions { + metadata?: StorageMetadata; + } + export interface CopyBlobOptions extends BlobSnapshotOptions { + sourceLeaseId?: string; + sourceAccessConditions: StorageAccessCondition; + } + + export interface UploadBlobOptions extends SetBlobPropertiesOptions { + metadata?: StorageMetadata; + speedSummary?: SpeedSummary; + parallelOperationThreadCount?: number; + storeBlobContentMD5?: boolean; + useTransactionalMD5?: boolean; + } + export interface CreatePagesOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; + } + export interface PageRangeOptions extends LeaseIdOptions { + snapshotId?: string; + rangeStart?: number; + rangeEnd?: number; + } + + export interface UploadBlockBlobOptions extends UploadBlobOptions { + blockIdPrefix?: string; + } + export interface CreateBlockOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; + } + + export interface LeaseOptions extends AccessConditionsOptions { + leaseDuration?: string; + proposedLeaseId?: string; + } + export interface BreakLeaseOptions extends AccessConditionsOptions { + leaseBreakPeriod?: number; + } + + export interface SharedAccessSignatureResult { + baseUrl: string; + path: string; + queryString: { + se: string; + sp: string; + sr: string; + sv: string; + sig: string; + }; + url: () => string; + } + export interface BlobHeaders { + cacheControl?: string; + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentDisposition?: string; + } + export interface PageRange { + start: number; + end: number; + } + export interface BlockList { + LatestBlocks: string[]; + CommittedBlocks: string[]; + UncommittedBlocks: string[]; + } + export interface StorageAccessCondition { + "If-Modified-Since": Date; + "If-Unmodified-Since": Date; + "If-Match": string; + "If-None-Match": string; + } + //#endregion + //#region QueueService Interfaces + export interface ListQueuesOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; + } + export interface ListQueuesCallback { + (err: Error, queues: QueueResult[], continuationToken: ContinuationToken, response: WebResponse): void; + } + + export interface CreateQueueMessageOptions extends TimeoutIntervalOptions { + messagettl?: number; + visibilitytimeout?: number; + } + export interface PeekQueueMessagesOptions extends TimeoutIntervalOptions { + numofmessages?: number; + } + export interface GetQueueMessagesOptions extends PeekQueueMessagesOptions { + peekonly?: boolean; + visibilitytimeout?: number; + } + export interface UpdateQueueMessagesOptions extends TimeoutIntervalOptions { + messagetext?: string; + } + //#endregion + + //#region RoleEnvironment Interfaces + export interface Role { + name: string; + instances: { + [instanceId: string]: RoleInstance; + }; + } + export interface RoleInstance { + id: string; + faultDomain: string; + updateDomain: string; + endpoints: { + [endpoint: string]: RoleInstanceEndpoint + }; + } + export interface RoleInstanceEndpoint { + protocol: string; + address: string; + port: number; + } + export interface RoleLocalResource { + name: string; + path: string; + maximumSizeInMegabytes: number; + } + //#endregion + //#region ConnectionStringParser Interfaces + export interface ConnectionStringParseOptions { + skipLowerCase: boolean; + } + //#endregion + //#region Validate Interfaces + export interface ClusterCreationOptions { + name: string; + location: string; + defaultStorageAccountName: string; + defaultStorageAccountKey: string; + defaultStorageContainer: string; + user: string; + password: string; + nodes: number; + additionalStorageAccounts?: { + name: string; + key: string; + }[]; + oozieMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; + hiveMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; + } + //#endregion + //#region ServiceSettings Interfaces + export interface Requirement { + SettingName: string; + SettingPredicate: Function; + } + export interface ValidatorFunction { + (userSettings: Dictionary): any; + } + //#endregion //#endregion //#region Un-exported internal classes class StorageServiceClient extends ServiceClient { static incorrectStorageAccountErr: string; static incorrectStorageAccessKeyErr: string; - static getStorageSettings(connectionString: string) : StorageServiceSettings; + static getStorageSettings(connectionString: string): StorageServiceSettings; static getStorageSettings(storageAccount?: string, storageAccessKey?: string, host?: string): StorageServiceSettings; apiVersion: string; @@ -404,5 +1873,4 @@ declare module "azure" { //#endregion export function isEmulated(): boolean; - } diff --git a/node/node-tests.ts b/node/node-tests.ts index e9ef58dbb..a8475a8dc 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -59,6 +59,10 @@ class Networker extends events.EventEmitter { } } +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + url.format(url.parse('http://www.example.com/xyz')); // https://google.com/search?q=you're%20a%20lizard%2C%20gary @@ -69,6 +73,10 @@ url.format({ query: { q: "you're a lizard, gary" } }); +var helloUrl = url.parse('http://example.com/?hello=world', true) +assert.equal(helloUrl.query.hello, 'world'); + + // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); diff --git a/node/node.d.ts b/node/node.d.ts index 4140a8c4b..7893f6fc6 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -658,7 +658,7 @@ declare module "url" { host: string; pathname: string; search: string; - query: string; + query: any; // string | Object slashes: boolean; hash?: string; path?: string; diff --git a/npm/npm-tests.ts b/npm/npm-tests.ts new file mode 100644 index 000000000..9a8578264 --- /dev/null +++ b/npm/npm-tests.ts @@ -0,0 +1,28 @@ +/** +* Test suite created by Maxime LUCE +* +* Created by using code samples from https://github.com/npm/npm#using-npm-programmatically. +*/ + +/// +/// + +import npm = require("npm"); + +npm.load({}, function (er) { + if (er) { + return console.error(er); + } + + npm.commands.install(["some", "args"], function (er, data) { + if (er) { + return console.error(er); + } + + // command succeeded, and data might have some info + }); + + npm.on("log", function (message: string) { + console.log(message); + }); +}) diff --git a/npm/npm.d.ts b/npm/npm.d.ts new file mode 100644 index 000000000..e81fb6c5b --- /dev/null +++ b/npm/npm.d.ts @@ -0,0 +1,461 @@ +// Type definitions for npm 2.0.0 +// Project: https://github.com/npm/npm +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module NPM { + export interface Static extends NodeJS.EventEmitter { + config: Config; + commands: Commands; + rollbacks: any[]; + spinner: Spinner; + fullList: string[]; + abbrevs: Dictionary; + + prefix: string; + bin: string; + globalBin: string; + dir: string; + globalDir: string; + root: string; + cache: string; + tmp: string; + + + load(cli: ConfigOptions): void; + load(callback: SimpleCallback): void; + load(cli: ConfigOptions, callback: SimpleCallback): void; + + deref(command: string): string; + } + + //#region Commands Interfaces + + export interface Commands { + // Commands + install: CommandFunction; + uninstall: CommandFunction; + cache: CommandFunction; + config: CommandFunction; + set: CommandFunction; + get: CommandFunction; + update: CommandFunction; + outdated: CommandFunction; + prune: CommandFunction; + submodule: CommandFunction; + pack: CommandFunction; + dedupe: CommandFunction; + + rebuild: CommandFunction; + link: CommandFunction; + + publish: CommandFunction; + star: CommandFunction; + stars: CommandFunction; + tag: CommandFunction; + adduser: CommandFunction; + unpublish: CommandFunction; + owner: CommandFunction; + deprecate: CommandFunction; + shrinkwrap: CommandFunction; + + help: CommandFunction; + "help-search": CommandFunction; + ls: CommandFunction; + search: CommandFunction; + view: CommandFunction; + init: CommandFunction; + version: CommandFunction; + edit: CommandFunction; + explore: CommandFunction; + docs: CommandFunction; + repo: CommandFunction; + bugs: CommandFunction; + faq: CommandFunction; + root: CommandFunction; + prefix: CommandFunction; + bin: CommandFunction; + whoami: CommandFunction; + + test: CommandFunction; + stop: CommandFunction; + start: CommandFunction; + restart: CommandFunction; + "run-script": CommandFunction; + completion: CommandFunction; + + //Aliases + rm: CommandFunction; // uninstall + r: CommandFunction; // uninstall + un: CommandFunction; // uninstall + unlink: CommandFunction; // uninstall + remove: CommandFunction; // uninstall + rb: CommandFunction; // rebuild + list: CommandFunction; // ls + la: CommandFunction; // ls + ll: CommandFunction; // ls + i: CommandFunction; // install + isntall: CommandFunction; // install + up: CommandFunction; // update + c: CommandFunction; // config + info: CommandFunction; // view + show: CommandFunction; // view + find: CommandFunction; // search + s: CommandFunction; // search + se: CommandFunction; // search + author: CommandFunction; // owner + home: CommandFunction; // docs + issues: CommandFunction; // bugs + unstar: CommandFunction; // star + apihelp: CommandFunction; // help + long: CommandFunction; // adduser + "add-user": CommandFunction; // adduser + tst: CommandFunction; // test + t: CommandFunction; // test + "find-dupes": CommandFunction; // dedupe + ddp: CommandFunction; // dedupe + v: CommandFunction; // view + + // plumbing + build: CommandFunction; + unbuild: CommandFunction; + xmas: CommandFunction; + substack: CommandFunction; + visnup: CommandFunction; + + } + + export interface CommandFunction { + (args: string[], callback: CommandCallback): void; + } + + export interface CommandCallback { + (err?: Error, result?: any, result2?: any, result3?: any, result4?: any): void; + } + + //#endregion + + //#region Other Interfaces + + export interface Spinner { + int: string; + started: boolean; + start(): void; + stop(): void; + } + + //#endregion + + //#region Config Interfaces + + export interface ConfigStatic { + new (base: Config): Config; + (base: Config): Config; + } + + export interface Config { + loaded: boolean; + sources: Dictionary; + rootConf: Config; + usingBuiltin: boolean; + root?: Config; + Conf: ConfigStatic; + defs: ConfigDefs; + + get(setting: string): string; + set(setting: string, value: string): void; + + loadPrefix(cb: ErrorCallback): void; + loadCAFile(caFilePath: string, cb: ErrorCallback): void; + loadUid(cb: SimpleCallback): void; + setUser(cb: ErrorCallback): void; + findPrefix(prefix: string, cb: SimpleCallback): void; + getCredentialsByURI(uri: string): Credentials; + setCredentialsByURI(uri: string, cred: Credentials): void; + + loadExtras(cb: ErrorCallback): void; + save(where: string, cb: ErrorCallback): Config; + addFile(file: string, name: string): Config; + parse(content: string, file: string): any; + add(data: Object, marker: Object): any; + addEnv(env: Dictionary): any; + } + + export interface ConfigDefs { + defaults: ConfigOptions; + types: ConfigTypes; + } + + export interface ConfigOptions { + "always-auth"?: boolean; + "bin-links"?: boolean; + browser?: string; + + ca?: any; // string | string[] + cafile?: string; + + cache?: string; + + "cache-lock-stale"?: number; + "cache-lock-retries"?: number; + "cache-lock-wait"?: number; + + "cache-max"?: number; + "cache-min"?: number; + + cert?: string; + + color?: any; // boolean | string ("always") + depth?: number; + description?: boolean; + dev?: boolean; + editor?: string; + "engine-strict"?: boolean; + force?: boolean; + + "fetch-retries"?: number; + "fetch-retry-factor"?: number; + "fetch-retry-mintimeout"?: number; + "fetch-retry-maxtimeout"?: number; + + git?: string; + "git-tag-version"?: boolean; + + global?: boolean; + globalconfig?: string; + group?: any; // number | string + heading?: string; + "ignore-scripts"?: boolean; + "init-module"?: string; + "init.author.name"?: string; + "init.author.email"?: string; + "init.author.url"?: string; + "init.version"?: string; + "init.license"?: string; + json?: boolean; + key?: string; + link?: boolean; + "local-address"?: string; + loglevel?: string; + logstream?: NodeJS.ReadWriteStream; + long?: boolean; + message?: string; + "node-version"?: string; + npat?: boolean; + "onload-script"?: boolean; + optional?: boolean; + parseable?: boolean; + prefix?: string; + production?: boolean; + "proprietary-attribs"?: boolean; + proxy?: any; // boolean | string + "https-proxy"?: string; + "user-agent"?: string; + "rebuild-bundle"?: boolean; + registry?: string; + rollback?: boolean; + save?: boolean; + "save-bundle"?: boolean; + "save-dev"?: boolean; + "save-exact"?: boolean; + "save-optional"?: boolean; + "save-prefix"?: string; + scope?: string; + searchopts?: string; + searchexclude?: string; + searchsort?: string; + shell?: string; + shrinkwrap?: boolean; + "sign-git-tag"?: boolean; + spin?: any; // boolean | string ("always") + "strict-ssl"?: boolean; + tag?: string; + tmp?: string; + unicode?: boolean; + "unsafe-perm"?: boolean; + usage?: boolean; + user?: any; // string | number + userconfig?: string; + umask?: number; + version?: boolean; + versions?: boolean; + viewer?: string; + + _exit?: boolean; + } + + export interface ConfigTypes { + "always-auth": typeof Boolean; + "bin-links": typeof Boolean; + browser: any[]; + + ca: any[]; + cafile: typeof String; + cache: typeof String; + + "cache-lock-stale": typeof Number; + "cache-lock-retries": typeof Number; + "cache-lock-wait": typeof Number; + + "cache-max": typeof Number; + "cache-min": typeof Number; + + cert: typeof String; + + color: any[]; + depth: typeof Number; + description: typeof Boolean; + dev: typeof Boolean; + editor: typeof String; + "engine-strict": typeof Boolean; + force: typeof Boolean; + + "fetch-retries": typeof Number; + "fetch-retry-factor": typeof Number; + "fetch-retry-mintimeout": typeof Number; + "fetch-retry-maxtimeout": typeof Number; + + git: typeof String; + "git-tag-version": typeof Boolean; + + global: typeof Boolean; + globalconfig: typeof String; + group: any[]; + heading: typeof String; + "ignore-scripts": typeof Boolean; + "init-module": typeof String; + "init.author.name": typeof String; + "init.author.email": typeof String; + "init.author.url": typeof String; + "init.version": typeof String; + "init.license": typeof String; + json: typeof Boolean; + key: any[]; + link: typeof Boolean; + "local-address": typeof String; + loglevel: any[]; + logstream: any; // typeof stream.Stream + long: typeof Boolean; + message: typeof String; + "node-version": any[]; + npat: typeof Boolean; + "onload-script": any[]; + optional: typeof Boolean; + parseable: typeof Boolean; + prefix: typeof String; + production: typeof Boolean; + "proprietary-attribs": typeof Boolean; + proxy: any[]; + "https-proxy": any[]; + "user-agent": typeof String; + "rebuild-bundle": Boolean; + registry: any[]; + rollback: typeof Boolean; + save: typeof Boolean; + "save-bundle": typeof Boolean; + "save-dev": typeof Boolean; + "save-exact": typeof Boolean; + "save-optional": typeof Boolean; + "save-prefix": typeof String; + scope: typeof String; + searchopts: typeof String; + searchexclude: any[]; + searchsort: any[]; + shell: typeof String; + shrinkwrap: typeof Boolean; + "sign-git-tag": typeof Boolean; + spin: any[]; + "strict-ssl": typeof Boolean; + tag: typeof String; + tmp: typeof String; + unicode: typeof Boolean; + "unsafe-perm": typeof Boolean; + usage: typeof Boolean; + user: any; // String | Number + userconfig: typeof String; + umask: typeof Number; + version: typeof Boolean; + versions: typeof Boolean; + viewer: typeof String; + + _exit: typeof Boolean; + } + + export interface ConfigShorthands { + s: any[]; + d: any[]; + dd: any[]; + ddd: any[]; + noreg: any[]; + N: any[]; + reg: any[]; + "no-reg": any[]; + silent: any[]; + verbose: any[]; + quiet: any[]; + q: any[]; + h: any[]; + H: any[]; + "?": any[]; + help: any[]; + v: any[]; + f: any[]; + gangster: any[]; + gangsta: any[]; + desc: any[]; + "no-desc": any[]; + "local": any[]; + l: any[]; + m: any[]; + p: any[]; + porcelain: any[]; + g: any[]; + S: any[]; + D: any[]; + E: any[]; + O: any[]; + y: any[]; + n: any[]; + B: any[]; + C: any[]; + } + + export interface ConfigSource { + path: string; + type: string; + } + + export interface Credentials { + scope: string; + token?: string; + password?: string; + username?: string; + email?: string; + auth?: string; + } + + //#endregion + + //#region Utilities Interfaces + + export interface Dictionary { + [key: string]: T; + } + + export interface ErrorCallback { + (err?: Error): void; + } + + export interface SimpleCallback { + (err?: Error, result?: T): void; + } + + //#endregion +} + +declare module "npm" { + var npm: NPM.Static; + export = npm; +} diff --git a/passport-local/passport-local-tests.ts b/passport-local/passport-local-tests.ts new file mode 100644 index 000000000..de799a4d8 --- /dev/null +++ b/passport-local/passport-local-tests.ts @@ -0,0 +1,53 @@ +/** + * Created by Maxime LUCE . + */ + +import express = require("express"); +import passport = require('passport'); +import local = require('passport-local'); + +//#region Test Models +interface IUser { + username: string; +} + +class User implements IUser { + public username: string; + public password: string; + + static findOne(user: IUser, callback: (err: Error, user: User) => void): void { + callback(null, new User()); + } + + verifyPassword(password: string): boolean { + return true; + } +} +//#endregion + +// Sample from https://github.com/jaredhanson/passport-local#configure-strategy +passport.use(new local.Strategy(function (username, password, done) { + User.findOne({ username: username }, function (err, user) { + if (err) { + return done(err); + } + + if (!user) { + return done(null, false); + } + + if (!user.verifyPassword(password)) { + return done(null, false); + } + + return done(null, user); + }); +})); + +// Sample from https://github.com/jaredhanson/passport-local#authenticate-requests +var app = express(); +app.post('/login', + passport.authenticate('local', { failureRedirect: '/login' }), + function (req, res) { + res.redirect('/'); + }); diff --git a/passport-local/passport-local.d.ts b/passport-local/passport-local.d.ts new file mode 100644 index 000000000..6b3cbef38 --- /dev/null +++ b/passport-local/passport-local.d.ts @@ -0,0 +1,33 @@ +// Type definitions for passport-local 1.0.0 +// Project: https://github.com/jaredhanson/passport-local +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'passport-local' { + + import passport = require('passport'); + import express = require('express'); + + interface IStrategyOptions { + usernameField?: string; + passwordField?: string; + } + + interface IVerifyOptions { + message: string; + } + + interface VerifyFunction { + (username: string, password: string, done: (error: any, user?: any, options?: IVerifyOptions) => void): void; + } + + class Strategy implements passport.Strategy { + constructor(options: IStrategyOptions, verify: VerifyFunction); + constructor(verify: VerifyFunction); + + name: string; + authenticate: (req: express.Request, options?: Object) => void; + } +} diff --git a/pickadate/pickadate-tests.ts b/pickadate/pickadate-tests.ts new file mode 100644 index 000000000..ac48a9856 --- /dev/null +++ b/pickadate/pickadate-tests.ts @@ -0,0 +1,243 @@ +/// +/// + +function testApiMethods(api: Pickadate.Api) { + api.clear(); + api.close(); + api.close(true); + api.get('value'); + api.get('value', 'yyyy-mm-dd'); + api.off('open'); + api.off('open', 'close', 'render'); + api.on('set', (context: {[key: string]: any}) => { }); + api.on('get', () => { }); + api.open(); + api.open(true); + api.render(); + api.render(true); + api.set('value', '2014-09-23'); + api.set({ + value: '2014-09-23', + max: new Date(2014, 12, 1) + }); + api.start(); + api.stop(); + api.trigger('open'); + + api.start().open().close().stop(); + + var pickerInputElement = api.$node; + pickerInputElement.show(); + + var pickerRootElement = api.$root; + pickerRootElement.show(); +} + +var datePickerInput = $("input.date"); + +datePickerInput.pickadate(); + +datePickerInput.pickadate({ + monthsFull: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + weekdaysFull: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + showMonthsShort: true, + showWeekdaysFull: true, + + today: 'Today', + clear: 'Clear', + close: 'Close', + + labelMonthNext: 'Next month', + labelMonthPrev: 'Previous month', + labelMonthSelect: 'Select a month', + labelYearSelect: 'Select a year', + + // Formats + format: 'd mmmm, yyyy', + formatSubmit: 'yyyy-mm-dd', + hiddenPrefix: 'foo', + hiddenSuffix: '_submit', + hiddenName: 'bar', + + // Editable input + editable: true, + + // Dropdown selectors + selectYears: true, + selectMonths: 10, + + // First day of the week + firstDay: 0, + + // Date limits + min: new Date(2013, 3, 20), + max: [2013, 7, 14], + + // Disable dates + disable: [ new Date(2013, 3, 21) ], + + // Root container + container: '.root-container', + + // Events + onStart: () => { }, + onRender: () => { }, + onOpen: () => { }, + onClose: () => { }, + onSet: (context: {[key: string]: any}) => { }, + onStop: () => { } +}); + +datePickerInput.pickadate({ + klass: { + // The element states + input: 'picker__input', + active: 'picker__input--active', + + // The root picker and states * + picker: 'picker', + opened: 'picker--opened', + focused: 'picker--focused', + + // The picker holder + holder: 'picker__holder', + + // The picker frame, wrapper, and box + frame: 'picker__frame', + wrap: 'picker__wrap', + box: 'picker__box', + + // The picker header + header: 'picker__header', + + // Month navigation + navPrev: 'picker__nav--prev', + navNext: 'picker__nav--next', + navDisabled: 'picker__nav--disabled', + + // Month & year labels + month: 'picker__month', + year: 'picker__year', + + // Month & year dropdowns + selectMonth: 'picker__select--month', + selectYear: 'picker__select--year', + + // Table of dates + table: 'picker__table', + + // Weekday labels + weekdays: 'picker__weekday', + + // Day states + day: 'picker__day', + disabled: 'picker__day--disabled', + selected: 'picker__day--selected', + highlighted: 'picker__day--highlighted', + now: 'picker__day--today', + infocus: 'picker__day--infocus', + outfocus: 'picker__day--outfocus', + + // The picker footer + footer: 'picker__footer', + + // Today, clear, & close buttons + buttonClear: 'picker__button--clear', + buttonClose: 'picker__button--close', + buttonToday: 'picker__button--today' + } +}); + +var datePickerApi = datePickerInput.pickadate('picker'); + +datePickerInput.pickadate('open'); +datePickerInput.pickadate('get', 'value'); + +testApiMethods(datePickerApi); + +// ==================================================================================================================== + +var timePickerInput = $("input.time"); + +timePickerInput.pickatime(); + +timePickerInput.pickatime({ + // Translations and clear button + clear: 'Clear', + + // Formats + format: 'h:i A', + formatLabel: 'h:i a', + formatSubmit: 'HH:i', + hiddenPrefix: 'prefix__', + hiddenSuffix: '__suffix', + + // Editable input + editable: true, + + // Time intervals + interval: 30, + + // Time limits + min: new Date(2013, 3, 20, 7), + max: [7, 14], + + // Disable times + disable: [ new Date(2013, 3, 21, 7) ], + + // Root container + container: '.root-container', + + // Events + onStart: () => { }, + onRender: () => { }, + onOpen: () => { }, + onClose: () => { }, + onSet: (context: {[key: string]: any}) => { }, + onStop: () => { } +}); + +timePickerInput.pickatime({ + klass: { + // The element states + input: 'picker__input', + active: 'picker__input--active', + + // The root picker and states * + picker: 'picker picker--time', + opened: 'picker--opened', + focused: 'picker--focused', + + // The picker holder + holder: 'picker__holder', + + // The picker frame, wrapper, and box + frame: 'picker__frame', + wrap: 'picker__wrap', + box: 'picker__box', + + // List of times + list: 'picker__list', + listItem: 'picker__list-item', + + // Time states + disabled: 'picker__list-item--disabled', + selected: 'picker__list-item--selected', + highlighted: 'picker__list-item--highlighted', + viewset: 'picker__list-item--viewset', + now: 'picker__list-item--now', + + // Clear button + buttonClear: 'picker__button--clear' + } +}); + +var timePickerApi = timePickerInput.pickatime('picker'); + +timePickerInput.pickatime('open'); +timePickerInput.pickatime('get', 'value'); + +testApiMethods(timePickerApi); + diff --git a/pickadate/pickadate.d.ts b/pickadate/pickadate.d.ts new file mode 100644 index 000000000..d21550d00 --- /dev/null +++ b/pickadate/pickadate.d.ts @@ -0,0 +1,317 @@ +// Type definitions for pickadate.js 3.5.4 +// Project: https://github.com/amsul/pickadate.js +// Definitions by: Adi Dahiya +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Pickadate { + + export interface Api { + /** + * Clear the value in the picker's input element. + */ + clear(): Pickadate.Api; + + /** + * Close the picker. + * + * @param keepFocus whether to retain focus on the input element (default: false) + */ + close(keepFocus?: boolean): Pickadate.Api; + + /** + * Get the properties, objects, and states of the picker. + * + * @param field one of [ "value", "select", "highlight", "view", "min", "max", "open", "start", "id", "disable", "enable" ] + * @param format string formatter (available for certain fields) + */ + get(field: string, format?: string): any; + + /** + * Unbind callbacks that are bound using the `on` method. + * @param methodName one of [ "open, "close", "render", "start", "stop", "set" ] + */ + off(methodName: string, ...moreMethodNames: string[]): Pickadate.Api; + + /** + * Attach an event handler for the picker. Only "set" events callbacks receive a "context" object. + * + * @param methodName event to attach handler to, one of [ "open", "close", "render", "start", "stop", or "set" ] + * @param callback event handler + */ + on(methodName: string, callback: (context?: any) => void): Pickadate.Api; + + /** + * Open the picker. + * + * @param keepFocus whether to focus the input element (default: true) + */ + open(keepFocus?: boolean): Pickadate.Api; + + /** + * Refresh the picker after adding something to the holder. + * By default, only the “face” of the picker (i.e. the box element), has its contents re-rendered. + * + * @param fromRoot whether to render the entire picker from the root up (default: false) + */ + render(fromRoot?: boolean): Pickadate.Api; + + /** + * Set the properties, objects, and states of the picker. + * + * @param field one of [ "clear", "select", "highlight", "view", "min", "max", "disable", "enable", "interval" ] + * @param value the thing you want to set + */ + set(field: string, value: any, options?: {[key: string]: any}): Pickadate.Api; + /** + * Batch set picker options after initialization. + */ + set(values: {[field: string]: any}, options?: {[key: string]: any}): Pickadate.Api; + + /** + * Rebuild the picker. + */ + start(): Pickadate.Api; + + /** + * Destroy the picker. + */ + stop(): Pickadate.Api; + + /** + * Trigger a picker event. + * @param eventName the event to trigger + */ + trigger(eventName: string): Pickadate.Api; + + /** + * The picker's relative element. + */ + $node: JQuery; + + /** + * The picker's relative root holder element. + */ + $root: JQuery; + + /** + * The picker's relative hidden element, which is undefined if there's no formatSubmit option. + * This is meant to be mostly for internal use. + */ + _hidden: JQuery; + } + + export interface DateOptions { + // String and translations + monthsFull?: string[]; + monthsShort?: string[]; + weekdaysFull?: string[]; + weekdaysShort?: string[] + showMonthsShort?: boolean; + showWeekdaysFull?: boolean; + + // Button labels (if falsy, the corresponding button is disabled) + today?: string; + clear?: string; + close?: string; + + // Accessibility labels + labelMonthNext?: string; + labelMonthPrev?: string; + labelMonthSelect?: string; + labelYearSelect?: string; + + // Formats + format?: string; + formatSubmit?: string; + hiddenPrefix?: string; + hiddenSuffix?: string; + hiddenName?: string; + + // Editable input + editable?: boolean; + + // Number of months to show in the month selection dropdown OR a boolean + selectMonths?: any; + // Number of years to show in the month selection dropdown OR a boolean + selectYears?: any; + + // First day of the week + firstDay?: number + + // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + disable?: any[]; + + // Root container selector + container?: string + + // Events + onStart?: () => void; + onRender?: () => void; + onOpen?: () => void; + onClose?: () => void; + onSet?: (context: {[key: string]: any}) => void; + onStop?: () => void; + + // Classes + klass?: DateKlassOptions; + } + + export interface DateKlassOptions { + // The element states + input?: string; + active?: string; + + // The root picker and states + picker?: string; + opened?: string; + focused?: string; + + // The picker holder + holder?: string; + + // The picker frame, wrapper, and box + frame?: string; + wrap?: string; + box?: string; + + // The picker header + header?: string; + + // Month navigation + navPrev?: string; + navNext?: string; + navDisabled?: string; + + // Month & year labels + month?: string; + year?: string; + + // Month & year dropdowns + selectMonth?: string; + selectYear?: string; + + // Table of dates + table?: string; + + // Weekday labels + weekdays?: string; + + // Day states + day?: string; + disabled?: string; + selected?: string; + highlighted?: string; + now?: string; + infocus?: string; + outfocus?: string; + + // The picker footer + footer?: string; + + // Today, clear, & close buttons + buttonClear?: string; + buttonClose?: string; + buttonToday?: string + } + + export interface TimeOptions { + // Translations and clear button + clear?: string; + + // Formats + format?: string; + formatLabel?: string; + formatSubmit?: string; + hiddenPrefix?: string; + hiddenSuffix?: string; + + // Editable input + editable?: boolean; + + // Time intervals + interval?: number; + + // Time limits (can be Dates, arrays formatted as [HOUR, MINUTE], integers, or booleans) + min?: any; + max?: any; + + // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + disable?: any[]; + + // Root container selector + container?: string + + // Events + onStart?: () => void; + onRender?: () => void; + onOpen?: () => void; + onClose?: () => void; + onSet?: (context: {[key: string]: any}) => void; + onStop?: () => void; + + // Classes + klass?: TimeKlassOptions; + } + + export interface TimeKlassOptions { + // The element states + input?: string; + active?: string; + + // The root picker and states + picker?: string; + opened?: string; + focused?: string; + + // The picker holder + holder?: string; + + // The picker frame, wrapper, and box + frame?: string; + wrap?: string; + box?: string; + + // List of times + list?: string; + listItem?: string; + + // Time states + disabled?: string; + selected?: string; + highlighted?: string; + viewset?: string; + now?: string; + + // Clear button + buttonClear?: string; + } +} + +interface JQuery { + /** + * Initialize a date picker. + */ + pickadate(options?: Pickadate.DateOptions): any; + + /** + * Access objects attached to the picker or invoke API methods after initialization. + * If keyword is "picker", this returns a PickadateApi. + * @param keyword "picker", an object name, or method name + * @param arguments any arguments to pass to the method + */ + pickadate(keyword: string, ...arguments: any[]): any; + + /** + * Initialize a time picker. + */ + pickatime(options?: Pickadate.TimeOptions): any; + + /** + * Access objects attached to the picker or invoke API methods after initialization. + * If keyword is "picker", this returns a PickadateApi. + * @param keyword "picker", an object name, or method name + * @param arguments any arguments to pass to the method + */ + pickatime(keyword: string, ...arguments: any[]): any; +} + diff --git a/precise/precise-tests.ts b/precise/precise-tests.ts new file mode 100644 index 000000000..029a69a3e --- /dev/null +++ b/precise/precise-tests.ts @@ -0,0 +1,9 @@ +/// + +import precise = require("precise"); + +var timer = precise().start(); + +setTimeout(function () { + console.log(timer.stop().diff()); +}, 1000); \ No newline at end of file diff --git a/precise/precise.d.ts b/precise/precise.d.ts new file mode 100644 index 000000000..e8af2245f --- /dev/null +++ b/precise/precise.d.ts @@ -0,0 +1,34 @@ +// Type definitions for precise +// Project: https://www.npmjs.org/package/precise +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "precise" { + /** + * Precise factory + */ + function _precise(): _precise.Precise; + + module _precise { + class Precise { + constructor(); + + /** + * Starts a timer + */ + start(): Precise; + + /** + * Stops a timer + */ + stop(): Precise; + + /** + * Returns the nanoseconds from `start()` to `stop()` + */ + diff(): number; + } + } + + export = _precise; +} diff --git a/radius/radius-tests.ts b/radius/radius-tests.ts new file mode 100644 index 000000000..2ce4d2c0d --- /dev/null +++ b/radius/radius-tests.ts @@ -0,0 +1,44 @@ +/// +/// + +import radius = require('radius'); + +var radius_secret: string = "shhhh" + +radius.add_dictionary("./"); +var encodedPacket: Buffer = radius.encode({ + code: "Access-Request", + secret: radius_secret, + attributes: { + "NAS-IP-Address": "10.5.5.5", + "User-Name": "me", + "User-Password": "its-a-secret" + } +}); + +var radiusPacket: radius.RadiusPacket = radius.decode({ + packet: encodedPacket, + secret: radius_secret +}); + +var response: Buffer; + +if (radiusPacket.attributes["User-Name"] == "me" && radiusPacket.attributes["User-Password"] == "its-a-secret") { + response = radius.encode_response({ + packet: radiusPacket, + code: "Access-Accept", + secret: radius_secret + }); +} else { + response = radius.encode_response({ + packet: radiusPacket, + code: "Access-Reject", + secret: radius_secret + }); +} + +console.log(radius.verify_response({ + request: encodedPacket, + response: response, + secret: radius_secret +})); \ No newline at end of file diff --git a/radius/radius.d.ts b/radius/radius.d.ts new file mode 100644 index 000000000..346b7b487 --- /dev/null +++ b/radius/radius.d.ts @@ -0,0 +1,106 @@ +// Type definitions for node-radius +// Project: https://github.com/retailnext/node-radius +// Definitions by: Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "radius" { + /** + * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. + **/ + export function decode(args: DecodeArgsWithSecret): RadiusPacket; + + /** + * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. + **/ + export function decode_without_secret(args: DecodeArgs): RadiusPacket; + + /** + * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. + **/ + export function encode(args: EncodeArgs): Buffer; + + /** + * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. + **/ + export function encode_response(args: EncodeResponseArgs): Buffer; + + /** + * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. + **/ + export function verify_response(args: VerifyResponseArgs):boolean; + + /** + * {@link https://github.com/retailnext/node-radius#radiusadd_dictionarypath} for more info. + * + * @param path Can be either a path to a file or a directory. + **/ + export function add_dictionary(path:string): void; + + export function unload_dictionaries(): void; + + + + + + + /** + * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. + **/ + interface DecodeArgs { + packet: Buffer; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. + **/ + interface DecodeArgsWithSecret extends DecodeArgs { + secret: string; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. + **/ + interface EncodeArgs { + code: string; + secret: string; + identifier?: number; + /** + * This can be an object: { attribute_name: attribute_value, ... }, + * an array within an array: [ [ attribute_name, attribute_value ], ... ], + * or if you haven't loaded a dictionary for the attributes: [ [ attribute_id, Buffer ], ... ]. + * + * Tag field-attributes can be specified like so: [ [ attribute_name, tag_number, attribute_value ] ... ] + **/ + attributes?: any; + add_message_authenticator?: boolean; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. + **/ + interface EncodeResponseArgs { + packet: RadiusPacket; + code: string; + secret: string; + attributes?: any; + } + + /** + * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. + **/ + interface VerifyResponseArgs { + request: Buffer; + response: Buffer; + secret: string; + } + + interface RadiusPacket { + code: string; + identifier: number; + length: number; + attributes: any; + raw_attributes: Array> + } +} \ No newline at end of file diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index 98ed2371b..e64fa7378 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -47,7 +47,7 @@ client.bitcount(str, numCallback); client.bitcount(str, num, num, numCallback); client.set(str, str, strCallback); client.get(str, strCallback); -client.exists(str, str, numCallback); +client.exists(str, numCallback); client.publish(str, value); client.subscribe(str); @@ -60,3 +60,5 @@ client.get(args); client.get(args, resCallback); client.set(args); client.set(args, resCallback); + +client.incr(str, resCallback); \ No newline at end of file diff --git a/redis/redis.d.ts b/redis/redis.d.ts index e31b130ac..913257d7c 100644 --- a/redis/redis.d.ts +++ b/redis/redis.d.ts @@ -1,12 +1,14 @@ // Type definitions for redis // Project: https://github.com/mranney/node_redis -// Definitions by: Carlos Ballesteros Velasco +// Definitions by: Carlos Ballesteros Velasco , Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/redis.d.ts declare module "redis" { - export function createClient(port_arg: number, host_arg: string, options: ClientOpts): RedisClient; + export function createClient(port_arg: number, host_arg?: string, options?: ClientOpts): RedisClient; + export function createClient(unix_socket: string, options?: ClientOpts): RedisClient; + export function createClient(options?: ClientOpts): RedisClient; export function print(err: Error, reply: any): void; export var debug_mode: boolean; @@ -14,17 +16,14 @@ declare module "redis" { (channel: string, message: any): void; } - interface ResCallback { - (err: Error, res: any): void; - } + interface CommandT { //This is a placeholder to be used eventually, to not have to define each command twice, or four times if all caps versions are to be implemented. + (args: any[], callback?: ResCallbackT): void; + (...args: any[]): void; + } - interface NumCallback { - (err: Error, reply: number): void; - } - - interface StringCallback { - (err: Error, reply: string): void; - } + interface ResCallbackT { + (err: Error, res: R): void; + } interface ServerInfo { redis_version: string; @@ -45,180 +44,310 @@ declare module "redis" { } interface RedisClient { - // event: connect - // event: error - // event: message - // event: pmessage - // event: subscribe - // event: psubscribe - // event: unsubscribe - // event: punsubscribe + // event: connect + // event: error + // event: message + // event: pmessage + // event: subscribe + // event: psubscribe + // event: unsubscribe + // event: punsubscribe - connected: boolean; - retry_delay: number; - retry_backoff: number; - command_queue: any[]; - offline_queue: any[]; - server_info: ServerInfo; + connected: boolean; + retry_delay: number; + retry_backoff: number; + command_queue: any[]; + offline_queue: any[]; + server_info: ServerInfo; - end(): void; + end(): void; - // Connection (http://redis.io/commands#connection) - auth(password: string, callback?: ResCallback): void; - ping(callback?: NumCallback): void; + // Connection (http://redis.io/commands#connection) + auth(password: string, callback?: ResCallbackT): void; + ping(callback?: ResCallbackT): void; - // Strings (http://redis.io/commands#strings) - append(key: string, value: string, callback?: NumCallback): void; - bitcount(key: string, callback?: NumCallback): void; - bitcount(key: string, start: number, end: number, callback?: NumCallback): void; - set(key: string, value: string, callback?: StringCallback): void; - get(key: string, callback?: StringCallback): void; - exists(key: string, value: string, callback?: NumCallback): void; + // Strings (http://redis.io/commands#strings) + append(key: string, value: string, callback?: ResCallbackT): void; + bitcount(key: string, callback?: ResCallbackT): void; + bitcount(key: string, start: number, end: number, callback?: ResCallbackT): void; + set(key: string, value: string, callback?: ResCallbackT): void; + get(key: string, callback?: ResCallbackT): void; + exists(key: string, value: string, callback?: ResCallbackT): void; - publish(channel: string, value: any): void; - subscribe(channel: string): void; - on(channel: string, handler: MessageHandler): void; + publish(channel: string, value: any): void; + subscribe(channel: string): void; + on(channel: string, handler: MessageHandler): void; - /* - commands = set_union([ - "get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", - "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", - "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", - "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", - "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", - "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", - "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", - "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", - "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", - "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); - */ + /* + commands = set_union([ + "get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", + "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", + "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", + "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", + "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", + "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", + "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", + "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", + "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", + "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); + */ - get(args: any[], callback?: ResCallback): void; - set(args: any[], callback?: ResCallback): void; - setnx(args: any[], callback?: ResCallback): void; - setex(args: any[], callback?: ResCallback): void; - append(args: any[], callback?: ResCallback): void; - strlen(args: any[], callback?: ResCallback): void; - del(args: any[], callback?: ResCallback): void; - exists(args: any[], callback?: ResCallback): void; - setbit(args: any[], callback?: ResCallback): void; - getbit(args: any[], callback?: ResCallback): void; - setrange(args: any[], callback?: ResCallback): void; - getrange(args: any[], callback?: ResCallback): void; - substr(args: any[], callback?: ResCallback): void; - incr(args: any[], callback?: ResCallback): void; - decr(args: any[], callback?: ResCallback): void; - mget(args: any[], callback?: ResCallback): void; - rpush(args: any[], callback?: ResCallback): void; - lpush(args: any[], callback?: ResCallback): void; - rpushx(args: any[], callback?: ResCallback): void; - lpushx(args: any[], callback?: ResCallback): void; - linsert(args: any[], callback?: ResCallback): void; - rpop(args: any[], callback?: ResCallback): void; - lpop(args: any[], callback?: ResCallback): void; - brpop(args: any[], callback?: ResCallback): void; - brpoplpush(args: any[], callback?: ResCallback): void; - blpop(args: any[], callback?: ResCallback): void; - llen(args: any[], callback?: ResCallback): void; - lindex(args: any[], callback?: ResCallback): void; - lset(args: any[], callback?: ResCallback): void; - lrange(args: any[], callback?: ResCallback): void; - ltrim(args: any[], callback?: ResCallback): void; - lrem(args: any[], callback?: ResCallback): void; - rpoplpush(args: any[], callback?: ResCallback): void; - sadd(args: any[], callback?: ResCallback): void; - srem(args: any[], callback?: ResCallback): void; - smove(args: any[], callback?: ResCallback): void; - sismember(args: any[], callback?: ResCallback): void; - scard(args: any[], callback?: ResCallback): void; - spop(args: any[], callback?: ResCallback): void; - srandmember(args: any[], callback?: ResCallback): void; - sinter(args: any[], callback?: ResCallback): void; - sinterstore(args: any[], callback?: ResCallback): void; - sunion(args: any[], callback?: ResCallback): void; - sunionstore(args: any[], callback?: ResCallback): void; - sdiff(args: any[], callback?: ResCallback): void; - sdiffstore(args: any[], callback?: ResCallback): void; - smembers(args: any[], callback?: ResCallback): void; - zadd(args: any[], callback?: ResCallback): void; - zincrby(args: any[], callback?: ResCallback): void; - zrem(args: any[], callback?: ResCallback): void; - zremrangebyscore(args: any[], callback?: ResCallback): void; - zremrangebyrank(args: any[], callback?: ResCallback): void; - zunionstore(args: any[], callback?: ResCallback): void; - zinterstore(args: any[], callback?: ResCallback): void; - zrange(args: any[], callback?: ResCallback): void; - zrangebyscore(args: any[], callback?: ResCallback): void; - zrevrangebyscore(args: any[], callback?: ResCallback): void; - zcount(args: any[], callback?: ResCallback): void; - zrevrange(args: any[], callback?: ResCallback): void; - zcard(args: any[], callback?: ResCallback): void; - zscore(args: any[], callback?: ResCallback): void; - zrank(args: any[], callback?: ResCallback): void; - zrevrank(args: any[], callback?: ResCallback): void; - hset(args: any[], callback?: ResCallback): void; - hsetnx(args: any[], callback?: ResCallback): void; - hget(args: any[], callback?: ResCallback): void; - hmset(args: any[], callback?: ResCallback): void; - hmget(args: any[], callback?: ResCallback): void; - hincrby(args: any[], callback?: ResCallback): void; - hdel(args: any[], callback?: ResCallback): void; - hlen(args: any[], callback?: ResCallback): void; - hkeys(args: any[], callback?: ResCallback): void; - hvals(args: any[], callback?: ResCallback): void; - hgetall(args: any[], callback?: ResCallback): void; - hexists(args: any[], callback?: ResCallback): void; - incrby(args: any[], callback?: ResCallback): void; - decrby(args: any[], callback?: ResCallback): void; - getset(args: any[], callback?: ResCallback): void; - mset(args: any[], callback?: ResCallback): void; - msetnx(args: any[], callback?: ResCallback): void; - randomkey(args: any[], callback?: ResCallback): void; - select(args: any[], callback?: ResCallback): void; - move(args: any[], callback?: ResCallback): void; - rename(args: any[], callback?: ResCallback): void; - renamenx(args: any[], callback?: ResCallback): void; - expire(args: any[], callback?: ResCallback): void; - expireat(args: any[], callback?: ResCallback): void; - keys(args: any[], callback?: ResCallback): void; - dbsize(args: any[], callback?: ResCallback): void; - auth(args: any[], callback?: ResCallback): void; - ping(args: any[], callback?: ResCallback): void; - echo(args: any[], callback?: ResCallback): void; - save(args: any[], callback?: ResCallback): void; - bgsave(args: any[], callback?: ResCallback): void; - bgrewriteaof(args: any[], callback?: ResCallback): void; - shutdown(args: any[], callback?: ResCallback): void; - lastsave(args: any[], callback?: ResCallback): void; - type(args: any[], callback?: ResCallback): void; - multi(args: any[], callback?: ResCallback): void; - exec(args: any[], callback?: ResCallback): void; - discard(args: any[], callback?: ResCallback): void; - sync(args: any[], callback?: ResCallback): void; - flushdb(args: any[], callback?: ResCallback): void; - flushall(args: any[], callback?: ResCallback): void; - sort(args: any[], callback?: ResCallback): void; - info(args: any[], callback?: ResCallback): void; - monitor(args: any[], callback?: ResCallback): void; - ttl(args: any[], callback?: ResCallback): void; - persist(args: any[], callback?: ResCallback): void; - slaveof(args: any[], callback?: ResCallback): void; - debug(args: any[], callback?: ResCallback): void; - config(args: any[], callback?: ResCallback): void; - subscribe(args: any[], callback?: ResCallback): void; - unsubscribe(args: any[], callback?: ResCallback): void; - psubscribe(args: any[], callback?: ResCallback): void; - punsubscribe(args: any[], callback?: ResCallback): void; - publish(args: any[], callback?: ResCallback): void; - watch(args: any[], callback?: ResCallback): void; - unwatch(args: any[], callback?: ResCallback): void; - cluster(args: any[], callback?: ResCallback): void; - restore(args: any[], callback?: ResCallback): void; - migrate(args: any[], callback?: ResCallback): void; - dump(args: any[], callback?: ResCallback): void; - object(args: any[], callback?: ResCallback): void; - client(args: any[], callback?: ResCallback): void; - eval(args: any[], callback?: ResCallback): void; - evalsha(args: any[], callback?: ResCallback): void; + get(args: any[], callback?: ResCallbackT): void; + get(...args: any[]): void; + set(args: any[], callback?: ResCallbackT): void; + set(...args: any[]): void; + setnx(args: any[], callback?: ResCallbackT): void; + setnx(...args: any[]): void; + setex(args: any[], callback?: ResCallbackT): void; + setex(...args: any[]): void; + append(args: any[], callback?: ResCallbackT): void; + append(...args: any[]): void; + strlen(args: any[], callback?: ResCallbackT): void; + strlen(...args: any[]): void; + del(args: any[], callback?: ResCallbackT): void; + del(...args: any[]): void; + exists(args: any[], callback?: ResCallbackT): void; + exists(...args: any[]): void; + setbit(args: any[], callback?: ResCallbackT): void; + setbit(...args: any[]): void; + getbit(args: any[], callback?: ResCallbackT): void; + getbit(...args: any[]): void; + setrange(args: any[], callback?: ResCallbackT): void; + setrange(...args: any[]): void; + getrange(args: any[], callback?: ResCallbackT): void; + getrange(...args: any[]): void; + substr(args: any[], callback?: ResCallbackT): void; + substr(...args: any[]): void; + incr(args: any[], callback?: ResCallbackT): void; + incr(...args: any[]): void; + decr(args: any[], callback?: ResCallbackT): void; + decr(...args: any[]): void; + mget(args: any[], callback?: ResCallbackT): void; + mget(...args: any[]): void; + rpush(...args: any[]): void; + lpush(args: any[], callback?: ResCallbackT): void; + lpush(...args: any[]): void; + rpushx(args: any[], callback?: ResCallbackT): void; + rpushx(...args: any[]): void; + lpushx(args: any[], callback?: ResCallbackT): void; + lpushx(...args: any[]): void; + linsert(args: any[], callback?: ResCallbackT): void; + linsert(...args: any[]): void; + rpop(args: any[], callback?: ResCallbackT): void; + rpop(...args: any[]): void; + lpop(args: any[], callback?: ResCallbackT): void; + lpop(...args: any[]): void; + brpop(args: any[], callback?: ResCallbackT): void; + brpop(...args: any[]): void; + brpoplpush(args: any[], callback?: ResCallbackT): void; + brpoplpush(...args: any[]): void; + blpop(args: any[], callback?: ResCallbackT): void; + blpop(...args: any[]): void; + llen(args: any[], callback?: ResCallbackT): void; + llen(...args: any[]): void; + lindex(args: any[], callback?: ResCallbackT): void; + lindex(...args: any[]): void; + lset(args: any[], callback?: ResCallbackT): void; + lset(...args: any[]): void; + lrange(args: any[], callback?: ResCallbackT): void; + lrange(...args: any[]): void; + ltrim(args: any[], callback?: ResCallbackT): void; + ltrim(...args: any[]): void; + lrem(args: any[], callback?: ResCallbackT): void; + lrem(...args: any[]): void; + rpoplpush(args: any[], callback?: ResCallbackT): void; + rpoplpush(...args: any[]): void; + sadd(args: any[], callback?: ResCallbackT): void; + sadd(...args: any[]): void; + srem(args: any[], callback?: ResCallbackT): void; + srem(...args: any[]): void; + smove(args: any[], callback?: ResCallbackT): void; + smove(...args: any[]): void; + sismember(args: any[], callback?: ResCallbackT): void; + sismember(...args: any[]): void; + scard(args: any[], callback?: ResCallbackT): void; + scard(...args: any[]): void; + spop(args: any[], callback?: ResCallbackT): void; + spop(...args: any[]): void; + srandmember(args: any[], callback?: ResCallbackT): void; + srandmember(...args: any[]): void; + sinter(args: any[], callback?: ResCallbackT): void; + sinter(...args: any[]): void; + sinterstore(args: any[], callback?: ResCallbackT): void; + sinterstore(...args: any[]): void; + sunion(args: any[], callback?: ResCallbackT): void; + sunion(...args: any[]): void; + sunionstore(args: any[], callback?: ResCallbackT): void; + sunionstore(...args: any[]): void; + sdiff(args: any[], callback?: ResCallbackT): void; + sdiff(...args: any[]): void; + sdiffstore(args: any[], callback?: ResCallbackT): void; + sdiffstore(...args: any[]): void; + smembers(args: any[], callback?: ResCallbackT): void; + smembers(...args: any[]): void; + zadd(args: any[], callback?: ResCallbackT): void; + zadd(...args: any[]): void; + zincrby(args: any[], callback?: ResCallbackT): void; + zincrby(...args: any[]): void; + zrem(args: any[], callback?: ResCallbackT): void; + zrem(...args: any[]): void; + zremrangebyscore(args: any[], callback?: ResCallbackT): void; + zremrangebyscore(...args: any[]): void; + zremrangebyrank(args: any[], callback?: ResCallbackT): void; + zremrangebyrank(...args: any[]): void; + zunionstore(args: any[], callback?: ResCallbackT): void; + zunionstore(...args: any[]): void; + zinterstore(args: any[], callback?: ResCallbackT): void; + zinterstore(...args: any[]): void; + zrange(args: any[], callback?: ResCallbackT): void; + zrange(...args: any[]): void; + zrangebyscore(args: any[], callback?: ResCallbackT): void; + zrangebyscore(...args: any[]): void; + zrevrangebyscore(args: any[], callback?: ResCallbackT): void; + zrevrangebyscore(...args: any[]): void; + zcount(args: any[], callback?: ResCallbackT): void; + zcount(...args: any[]): void; + zrevrange(args: any[], callback?: ResCallbackT): void; + zrevrange(...args: any[]): void; + zcard(args: any[], callback?: ResCallbackT): void; + zcard(...args: any[]): void; + zscore(args: any[], callback?: ResCallbackT): void; + zscore(...args: any[]): void; + zrank(args: any[], callback?: ResCallbackT): void; + zrank(...args: any[]): void; + zrevrank(args: any[], callback?: ResCallbackT): void; + zrevrank(...args: any[]): void; + hset(args: any[], callback?: ResCallbackT): void; + hset(...args: any[]): void; + hsetnx(args: any[], callback?: ResCallbackT): void; + hsetnx(...args: any[]): void; + hget(args: any[], callback?: ResCallbackT): void; + hget(...args: any[]): void; + hmset(args: any[], callback?: ResCallbackT): void; + hmset(key: string, hash: any, callback?: ResCallbackT): void; + hmset(...args: any[]): void; + hmget(args: any[], callback?: ResCallbackT): void; + hmget(...args: any[]): void; + hincrby(args: any[], callback?: ResCallbackT): void; + hincrby(...args: any[]): void; + hdel(args: any[], callback?: ResCallbackT): void; + hdel(...args: any[]): void; + hlen(args: any[], callback?: ResCallbackT): void; + hlen(...args: any[]): void; + hkeys(args: any[], callback?: ResCallbackT): void; + hkeys(...args: any[]): void; + hvals(args: any[], callback?: ResCallbackT): void; + hvals(...args: any[]): void; + hgetall(args: any[], callback?: ResCallbackT): void; + hgetall(...args: any[]): void; + hgetall(key: string, callback?: ResCallbackT): void; + hexists(args: any[], callback?: ResCallbackT): void; + hexists(...args: any[]): void; + incrby(args: any[], callback?: ResCallbackT): void; + incrby(...args: any[]): void; + decrby(args: any[], callback?: ResCallbackT): void; + decrby(...args: any[]): void; + getset(args: any[], callback?: ResCallbackT): void; + getset(...args: any[]): void; + mset(args: any[], callback?: ResCallbackT): void; + mset(...args: any[]): void; + msetnx(args: any[], callback?: ResCallbackT): void; + msetnx(...args: any[]): void; + randomkey(args: any[], callback?: ResCallbackT): void; + randomkey(...args: any[]): void; + select(args: any[], callback?: ResCallbackT): void; + select(...args: any[]): void; + move(args: any[], callback?: ResCallbackT): void; + move(...args: any[]): void; + rename(args: any[], callback?: ResCallbackT): void; + rename(...args: any[]): void; + renamenx(args: any[], callback?: ResCallbackT): void; + renamenx(...args: any[]): void; + expire(args: any[], callback?: ResCallbackT): void; + expire(...args: any[]): void; + expireat(args: any[], callback?: ResCallbackT): void; + expireat(...args: any[]): void; + keys(args: any[], callback?: ResCallbackT): void; + keys(...args: any[]): void; + dbsize(args: any[], callback?: ResCallbackT): void; + dbsize(...args: any[]): void; + auth(args: any[], callback?: ResCallbackT): void; + auth(...args: any[]): void; + ping(args: any[], callback?: ResCallbackT): void; + ping(...args: any[]): void; + echo(args: any[], callback?: ResCallbackT): void; + echo(...args: any[]): void; + save(args: any[], callback?: ResCallbackT): void; + save(...args: any[]): void; + bgsave(args: any[], callback?: ResCallbackT): void; + bgsave(...args: any[]): void; + bgrewriteaof(args: any[], callback?: ResCallbackT): void; + bgrewriteaof(...args: any[]): void; + shutdown(args: any[], callback?: ResCallbackT): void; + shutdown(...args: any[]): void; + lastsave(args: any[], callback?: ResCallbackT): void; + lastsave(...args: any[]): void; + type(args: any[], callback?: ResCallbackT): void; + type(...args: any[]): void; + multi(args: any[], callback?: ResCallbackT): void; + multi(...args: any[]): void; + exec(args: any[], callback?: ResCallbackT): void; + exec(...args: any[]): void; + discard(args: any[], callback?: ResCallbackT): void; + discard(...args: any[]): void; + sync(args: any[], callback?: ResCallbackT): void; + sync(...args: any[]): void; + flushdb(args: any[], callback?: ResCallbackT): void; + flushdb(...args: any[]): void; + flushall(args: any[], callback?: ResCallbackT): void; + flushall(...args: any[]): void; + sort(args: any[], callback?: ResCallbackT): void; + sort(...args: any[]): void; + info(args: any[], callback?: ResCallbackT): void; + info(...args: any[]): void; + monitor(args: any[], callback?: ResCallbackT): void; + monitor(...args: any[]): void; + ttl(args: any[], callback?: ResCallbackT): void; + ttl(...args: any[]): void; + persist(args: any[], callback?: ResCallbackT): void; + persist(...args: any[]): void; + slaveof(args: any[], callback?: ResCallbackT): void; + slaveof(...args: any[]): void; + debug(args: any[], callback?: ResCallbackT): void; + debug(...args: any[]): void; + config(args: any[], callback?: ResCallbackT): void; + config(...args: any[]): void; + subscribe(args: any[], callback?: ResCallbackT): void; + subscribe(...args: any[]): void; + unsubscribe(args: any[], callback?: ResCallbackT): void; + unsubscribe(...args: any[]): void; + psubscribe(args: any[], callback?: ResCallbackT): void; + psubscribe(...args: any[]): void; + punsubscribe(args: any[], callback?: ResCallbackT): void; + punsubscribe(...args: any[]): void; + publish(args: any[], callback?: ResCallbackT): void; + publish(...args: any[]): void; + watch(args: any[], callback?: ResCallbackT): void; + watch(...args: any[]): void; + unwatch(args: any[], callback?: ResCallbackT): void; + unwatch(...args: any[]): void; + cluster(args: any[], callback?: ResCallbackT): void; + cluster(...args: any[]): void; + restore(args: any[], callback?: ResCallbackT): void; + restore(...args: any[]): void; + migrate(args: any[], callback?: ResCallbackT): void; + migrate(...args: any[]): void; + dump(args: any[], callback?: ResCallbackT): void; + dump(...args: any[]): void; + object(args: any[], callback?: ResCallbackT): void; + object(...args: any[]): void; + client(args: any[], callback?: ResCallbackT): void; + client(...args: any[]): void; + eval(args: any[], callback?: ResCallbackT): void; + eval(...args: any[]): void; + evalsha(args: any[], callback?: ResCallbackT): void; + evalsha(...args: any[]): void; + quit(args: any[], callback?: ResCallbackT): void; + quit(...args: any[]): void; } } diff --git a/request/request-tests.ts b/request/request-tests.ts index 986702c27..506205db8 100644 --- a/request/request-tests.ts +++ b/request/request-tests.ts @@ -69,7 +69,7 @@ var options: request.Options = { }, jar: value, - form: value, + form: obj, oauth: value, aws: aws, qs: obj, diff --git a/request/request.d.ts b/request/request.d.ts index fc03a7e19..d8d058d1d 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -61,7 +61,7 @@ declare module 'request' { uri?: string; callback?: (error: any, response: any, body: any) => void; jar?: any; // CookieJar - form?: FormData; + form?: any; // Object or string oauth?: OAuthOptions; aws?: AWSOptions; hawk ?: HawkOptions; diff --git a/rx/rx-lite.d.ts b/rx/rx-lite.d.ts index c7a148137..4b5acb81d 100644 --- a/rx/rx-lite.d.ts +++ b/rx/rx-lite.d.ts @@ -49,6 +49,8 @@ declare module Rx { export module helpers { function noop(): void; + function notDefined(value: any): boolean; + function isScheduler(value: any): boolean; function identity(value: T): T; function defaultNow(): number; function defaultComparer(left: any, right: any): boolean; @@ -394,6 +396,50 @@ declare module Rx { defer(observableFactory: () => Observable): Observable; defer(observableFactory: () => IPromise): Observable; empty(scheduler?: IScheduler): Observable; + + /** + * This method creates a new Observable sequence from an array object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param mapFn Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: T[], mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable; + /** + * This method creates a new Observable sequence from an array object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param [mapFn] Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: T[], mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable; + + /** + * This method creates a new Observable sequence from an array-like object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param mapFn Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: { length: number;[index: number]: T; }, mapFn: (value: T, index: number) => TResult, thisArg?: any, scheduler?: IScheduler): Observable; + /** + * This method creates a new Observable sequence from an array-like object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param [mapFn] Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(array: { length: number;[index: number]: T; }, mapFn?: (value: T, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable; + + /** + * This method creates a new Observable sequence from an array-like or iterable object. + * @param array An array-like or iterable object to convert to an Observable sequence. + * @param [mapFn] Map function to call on every element of the array. + * @param [thisArg] The context to use calling the mapFn if provided. + * @param [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. + */ + from(iterable: any, mapFn?: (value: any, index: number) => T, thisArg?: any, scheduler?: IScheduler): Observable; + fromArray(array: T[], scheduler?: IScheduler): Observable; fromArray(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable; diff --git a/rx/rx.async-lite.d.ts b/rx/rx.async-lite.d.ts index be13320c2..77dc23b57 100644 --- a/rx/rx.async-lite.d.ts +++ b/rx/rx.async-lite.d.ts @@ -16,46 +16,46 @@ declare module Rx { fromCallback: { // with single result callback without selector - (func: (callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: (result: TResult) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: (result: TResult) => any) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: (result: TResult) => any) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: (result: TResult) => any) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: (result: TResult) => any) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback with selector - (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): () => Observable; + (func: (arg1: T1, callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context: any, selector: (args: TCallbackResult[]) => TResult): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback without selector - (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: Function) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any function with selector - (func: Function, scheduler: IScheduler, context: any, selector: (args: TCallbackResult[]) => TResult): (...args: any[]) => Observable; + (func: Function, context: any, selector: (args: TCallbackResult[]) => TResult): (...args: any[]) => Observable; // with any function without selector - (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; + (func: Function, context?: any): (...args: any[]) => Observable; }; fromNodeCallback: { // with single result callback without selector - (func: (callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: T) => any) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: (err: any, result: T) => any) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: (err: any, result: T) => any) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: (err: any, result: T) => any) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: T) => any) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback with selector - (func: (callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler: IScheduler, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context: any, selector: (results: TC[]) => TR): () => Observable; + (func: (arg1: T1, callback: Function) => any, context: any, selector: (results: TC[]) => TR): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context: any, selector: (results: TC[]) => TR): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any callback without selector - (func: (callback: Function) => any, scheduler?: IScheduler, context?: any): () => Observable; - (func: (arg1: T1, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - (func: (arg1: T1, arg2: T2, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; + (func: (callback: Function) => any, context?: any): () => Observable; + (func: (arg1: T1, callback: Function) => any, context?: any): (arg1: T1) => Observable; + (func: (arg1: T1, arg2: T2, callback: Function) => any, context?: any): (arg1: T1, arg2: T2) => Observable; + (func: (arg1: T1, arg2: T2, arg3: T3, callback: Function) => any, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; // with any function with selector - (func: Function, scheduler: IScheduler, context: any, selector: (results: TC[]) => T): (...args: any[]) => Observable; + (func: Function, context: any, selector: (results: TC[]) => T): (...args: any[]) => Observable; // with any function without selector - (func: Function, scheduler?: IScheduler, context?: any): (...args: any[]) => Observable; + (func: Function, context?: any): (...args: any[]) => Observable; }; fromEvent(element: NodeList, eventName: string, selector?: (arguments: any[]) => T): Observable; diff --git a/rx/rx.async-tests.ts b/rx/rx.async-tests.ts index 9c3bce516..4f8c102c4 100644 --- a/rx/rx.async-tests.ts +++ b/rx/rx.async-tests.ts @@ -10,8 +10,8 @@ module Rx.Tests.Async { var sch: Rx.IScheduler; function start() { - obsNum = Rx.Observable.start(()=> 10, sch, obsStr); - obsNum = Rx.Observable.start(()=> 10, sch); + obsNum = Rx.Observable.start(()=> 10, obsStr, sch); + obsNum = Rx.Observable.start(() => 10, obsStr); obsNum = Rx.Observable.start(()=> 10); } @@ -27,38 +27,34 @@ module Rx.Tests.Async { // 0 arguments var func0: (cb: (result: number)=> void)=> void; obsNum = Rx.Observable.fromCallback(func0)(); - obsNum = Rx.Observable.fromCallback(func0, sch)(); - obsNum = Rx.Observable.fromCallback(func0, sch, obsStr)(); - obsNum = Rx.Observable.fromCallback(func0, sch, obsStr, (results: number[]) => results[0])(); + obsNum = Rx.Observable.fromCallback(func0, obsStr)(); + obsNum = Rx.Observable.fromCallback(func0, obsStr, (results: number[]) => results[0])(); // 1 argument var func1: (a: string, cb: (result: number)=> void)=> number; obsNum = Rx.Observable.fromCallback(func1)(""); - obsNum = Rx.Observable.fromCallback(func1, sch)(""); - obsNum = Rx.Observable.fromCallback(func1, sch, {})(""); - obsNum = Rx.Observable.fromCallback(func1, sch, {}, (results: number[]) => results[0])(""); + obsNum = Rx.Observable.fromCallback(func1, {})(""); + obsNum = Rx.Observable.fromCallback(func1, {}, (results: number[]) => results[0])(""); // 2 arguments var func2: (a: number, b: string, cb: (result: string) => number) => Date; obsStr = Rx.Observable.fromCallback(func2)(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch)(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch, {})(1, ""); - obsStr = Rx.Observable.fromCallback(func2, sch, {}, (results: string[]) => results[0])(1, ""); + obsStr = Rx.Observable.fromCallback(func2, {})(1, ""); + obsStr = Rx.Observable.fromCallback(func2, {}, (results: string[]) => results[0])(1, ""); // 3 arguments var func3: (a: number, b: string, c: boolean, cb: (result: string) => number) => Date; obsStr = Rx.Observable.fromCallback(func3)(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch)(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch, {})(1, "", true); - obsStr = Rx.Observable.fromCallback(func3, sch, {}, (results: string[]) => results[0])(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, {})(1, "", true); + obsStr = Rx.Observable.fromCallback(func3, {}, (results: string[]) => results[0])(1, "", true); // multiple results var func0m: (cb: (result1: number, result2: number, result3: number) => void) => void; - obsNum = Rx.Observable.fromCallback(func0m, sch, obsStr, (results: number[]) => results[0])(); + obsNum = Rx.Observable.fromCallback(func0m, obsStr, (results: number[]) => results[0])(); var func1m: (a: string, cb: (result1: number, result2: number, result3: number) => void) => void; - obsNum = Rx.Observable.fromCallback(func1m, sch, obsStr, (results: number[]) => results[0])(""); + obsNum = Rx.Observable.fromCallback(func1m, obsStr, (results: number[]) => results[0])(""); var func2m: (a: string, b: number, cb: (result1: string, result2: string, result3: string) => void) => void; - obsStr = Rx.Observable.fromCallback(func2m, sch, obsStr, (results: string[]) => results[0])("", 10); + obsStr = Rx.Observable.fromCallback(func2m, obsStr, (results: string[]) => results[0])("", 10); } function toPromise() { diff --git a/rx/rx.async.d.ts b/rx/rx.async.d.ts index 9370c828b..783f31d52 100644 --- a/rx/rx.async.d.ts +++ b/rx/rx.async.d.ts @@ -8,33 +8,33 @@ declare module Rx { interface ObservableStatic { - start(func: () => T, scheduler?: IScheduler, context?: any): Observable; + start(func: () => T, context?: any, scheduler?: IScheduler): Observable; - toAsync(func: () => TResult, scheduler?: IScheduler, context?: any): () => Observable; - toAsync(func: (arg1: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1) => Observable; - toAsync(func: (arg1?: T1) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1) => Observable; - toAsync(func: (...args: T1[]) => TResult, scheduler?: IScheduler, context?: any): (...args: T1[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2) => Observable; - toAsync(func: (arg1: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2) => Observable; - toAsync(func: (arg1: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, ...args: T2[]) => Observable; - toAsync(func: (arg1?: T1, ...args: T2[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, ...args: T2[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3) => Observable; - toAsync(func: (arg1: T1, arg2: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, ...args: T3[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, ...args: T3[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; - toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, scheduler?: IScheduler, context?: any): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: () => TResult, context?: any, scheduler?: IScheduler): () => Observable; + toAsync(func: (arg1: T1) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1) => Observable; + toAsync(func: (arg1?: T1) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1) => Observable; + toAsync(func: (...args: T1[]) => TResult, context?: any, scheduler?: IScheduler): (...args: T1[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2) => Observable; + toAsync(func: (arg1: T1, arg2?: T2) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2) => Observable; + toAsync(func: (arg1: T1, ...args: T2[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, ...args: T2[]) => Observable; + toAsync(func: (arg1?: T1, ...args: T2[]) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, ...args: T2[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3?: T3) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, arg3?: T3) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, arg3?: T3) => Observable; + toAsync(func: (arg1: T1, arg2: T2, ...args: T3[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, ...args: T3[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, ...args: T3[]) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, ...args: T3[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, arg3?: T3, arg4?: T4) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; + toAsync(func: (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => TResult, context?: any, scheduler?: IScheduler): (arg1?: T1, arg2?: T2, arg3?: T3, ...args: T4[]) => Observable; } } diff --git a/rx/rx.time-lite.d.ts b/rx/rx.time-lite.d.ts index a5b102827..7a7d8f46f 100644 --- a/rx/rx.time-lite.d.ts +++ b/rx/rx.time-lite.d.ts @@ -49,8 +49,8 @@ declare module Rx { interface ObservableStatic { interval(period: number, scheduler?: IScheduler): Observable; interval(dutTime: number, period: number, scheduler?: IScheduler): Observable; - timer(dueTime: number, period: number, scheduler: IScheduler): Observable; - timer(dueTime: number, scheduler: IScheduler): Observable; + timer(dueTime: number, period: number, scheduler?: IScheduler): Observable; + timer(dueTime: number, scheduler?: IScheduler): Observable; generateWithRelativeTime( initialState: TState, condition: (state: TState) => boolean, diff --git a/rx/rx.time.d.ts b/rx/rx.time.d.ts index 6efd7d9cf..2cdb1d56a 100644 --- a/rx/rx.time.d.ts +++ b/rx/rx.time.d.ts @@ -17,8 +17,8 @@ declare module Rx { } interface ObservableStatic { - timer(dueTime: Date, period: number, scheduler: IScheduler): Observable; - timer(dueTime: Date, scheduler: IScheduler): Observable; + timer(dueTime: Date, period: number, scheduler?: IScheduler): Observable; + timer(dueTime: Date, scheduler?: IScheduler): Observable; generateWithAbsoluteTime( initialState: TState, diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 9ce5321de..a4d1017aa 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3150,4 +3150,76 @@ declare module webdriver { declare module 'selenium-webdriver' { export = webdriver; -} \ No newline at end of file +} + +declare module 'selenium-webdriver/testing' { + + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/executors' { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. + */ + function createExecutor(url: any): webdriver.CommandExecutor; +} diff --git a/sendgrid/sendgrid-tests.ts b/sendgrid/sendgrid-tests.ts new file mode 100644 index 000000000..e7d34feb0 --- /dev/null +++ b/sendgrid/sendgrid-tests.ts @@ -0,0 +1,246 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/sendgrid/sendgrid-nodejs#usage + */ + +/// +/// + +import sg = require("sendgrid"); +var sendgrid = sg("api_user", "api_key"); + +/* + * Simple Usage + */ +var payload = { + to: 'to@example.com', + from: 'from@other.com', + subject: 'Saying Hi', + text: 'This is my first email through SendGrid' +}; +sendgrid.send(payload, function (err, json) { + if (err) { + console.error(err); + } + + console.log(json); +}); + +/** + * Email: + * https://github.com/sendgrid/sendgrid-nodejs#email + */ +var email = new sendgrid.Email({ + to: 'foo@bar.com', + from: 'you@yourself.com', + subject: 'Subject goes here', + text: 'Hello world' +}); + +sendgrid.send(email, function (err, json) { + if (err) { + return console.error(err); + } + console.log(json); +}); + +/** + * Setting Params + * https://github.com/sendgrid/sendgrid-nodejs#setting-params + */ +var email = new sendgrid.Email({ to: 'person@email.com' }); +email.to = "different@email.com"; +email.replyto = "reply-here@email.com"; +email.subject = "This is a subject"; + +/** + * addTo + * https://github.com/sendgrid/sendgrid-nodejs#addto + */ +var email = new sendgrid.Email(); +email.addTo('foo@bar.com'); +email.addTo('another@another.com'); +sendgrid.send(email, function (err, json) { }); + + +/** + * setFrom + * https://github.com/sendgrid/sendgrid-nodejs#setfrom + */ +var email = new sendgrid.Email(); +email.setFrom('foo@bar.com'); +sendgrid.send(email, function (err, json) { }); + +/** + * setSubject + * https://github.com/sendgrid/sendgrid-nodejs#setsubject + */ +var email = new sendgrid.Email(); +email.setSubject('Some subject'); +sendgrid.send(email, function (err, json) { }); + +/** + * setText + * https://github.com/sendgrid/sendgrid-nodejs#settext + */ +var email = new sendgrid.Email(); +email.setText('Some text'); +sendgrid.send(email, function (err, json) { }); + +/** + * setHtml + * https://github.com/sendgrid/sendgrid-nodejs#sethtml + */ +var email = new sendgrid.Email(); +email.setHtml('

Some html

'); +sendgrid.send(email, function (err, json) { }); + +/** + * addHeader + * https://github.com/sendgrid/sendgrid-nodejs#addheader + */ +var email = new sendgrid.Email(); +email.setHeaders({ full: 'hearts' }); // headers = {full: 'hearts'} +email.addHeader('spin', 'attack'); // headers = {full: 'hearts', spin: 'attack'} +email.addHeader('mask', 'salesman'); // headers = {full: 'hearts', spin: 'attack', mask: 'salesman'} +sendgrid.send(email, function (err, json) { }); + +/** + * setHeaders + * https://github.com/sendgrid/sendgrid-nodejs#setheaders + */ +var email = new sendgrid.Email(); +email.setHeaders({ full: 'hearts' }); // headers = {full: 'hearts'} +email.setHeaders({ mask: 'salesman' }); // headers = {mask: 'salesman'} +sendgrid.send(email, function (err, json) { }); + +/** + * addSubstitution + * https://github.com/sendgrid/sendgrid-nodejs#addsubstitution + */ +var email = new sendgrid.Email(); +email.addSubstitution('keep', 'secret'); // sub = {keep: ['secret']} +email.addSubstitution('other', ['one', 'two']); // sub = {keep: ['secret'], other: ['one', 'two']} + +/** + * setSubstitutions + * https://github.com/sendgrid/sendgrid-nodejs#setsubstitutions + */ +var email = new sendgrid.Email(); +email.setSubstitutions({ keep: ['secret'], other: ['one', 'two'] }); // sub = {keep: ['secret'], other: ['one', 'two']}); + +/** + * addSection + * https://github.com/sendgrid/sendgrid-nodejs#addsection + */ +var email = new sendgrid.Email(); +email.addSection({ '-charge-': 'This ship is useless.' }); // section = {'-charge-': 'This ship is useless.'} + +/** + * setSections + * https://github.com/sendgrid/sendgrid-nodejs#setsections + */ +var email = new sendgrid.Email(); +email.setSections({ '-charge-': 'This ship is useless.' }); // section = {'-charge-': 'This ship is useless.'} + +/** + * addUniqueArg + * https://github.com/sendgrid/sendgrid-nodejs#adduniquearg + */ +var email = new sendgrid.Email(); +email.setUniqueArgs({ cow: 'chicken' }); // unique_args = {cow: 'chicken'} +email.addUniqueArg({ cat: 'dog' }); // unique_args = {cow: 'chicken', cat: 'dog'} + +/** + * setUniqueArgs + * https://github.com/sendgrid/sendgrid-nodejs#setuniqueargs + */ +var email = new sendgrid.Email(); +email.setUniqueArgs({ cow: 'chicken' }); // unique_args = {cow: 'chicken'} +email.setUniqueArgs({ dad: 'proud' }); // unique_args = {dad: 'proud'} + + +/** + * addCategory + * https://github.com/sendgrid/sendgrid-nodejs#addcategory + */ +var email = new sendgrid.Email(); +email.addCategory('tactics'); // category = ['tactics'] +email.addCategory('advanced'); // category = ['tactics', 'advanced'] + +/** + * setCategories + * https://github.com/sendgrid/sendgrid-nodejs#setcategories + */ +var email = new sendgrid.Email(); +email.setCategories(['tactics']); // category = ['tactics'] +email.setCategories(['snowball-fight']); // category = ['snowball-fight'] + +/** + * addFilter + * https://github.com/sendgrid/sendgrid-nodejs#addfilter + */ +var email = new sendgrid.Email(); +email.addFilter('footer', 'enable', 1); +email.addFilter('footer', 'text/html', 'boo'); + +/** + * setFilters + * https://github.com/sendgrid/sendgrid-nodejs#setfilters + */ +var email = new sendgrid.Email(); +var email = new sendgrid.Email(); +email.setFilters({ + 'footer': { + 'setting': { + 'enable': 1, + 'text/plain': 'You can haz footers!' + } + } +}); + +/** + * addFile + * https://github.com/sendgrid/sendgrid-nodejs#addfile + */ +var email = new sendgrid.Email(); +email.addFile({ + filename: 'secret.txt', + content: new Buffer('You will never know....') +}); +// or +email.addFile({ + filename: 'icon.jpg', + url: 'http://i.imgur.com/2fDh8.jpg' +}); +// or +email.addFile({ + path: '../files/resume.txt' +}); +// or +email.addFile({ + cid: 'the_logo', // should match cid value in html + path: '../files/logo.png' +}); +email.setHtml('
Our logo:
'); + +/** + * Options - Changing URL + * https://github.com/sendgrid/sendgrid-nodejs#changing-url + */ +var sendgrid1 = sg('username', 'password', { "protocol": "http", "host": "sendgrid.org", "endpoint": "/send", "port": "80" }); +var sendgrid2 = sg('username', 'password', { "uri": "http://sendgrid.org:80/send" }); + +/** + * Options - Request + * https://github.com/sendgrid/sendgrid-nodejs#request + */ +var sendgrid3 = sg('username', 'password', { proxy: "http://localproxy:3128" }); +// or +import https = require('https'); +var agent = new https.Agent(); +agent.maxSockets = 500; // Set Max Sockets to 500 +var sendgrid4 = sg('username', 'password', { web: { pool: agent } }); + + diff --git a/sendgrid/sendgrid.d.ts b/sendgrid/sendgrid.d.ts new file mode 100644 index 000000000..7f644b65b --- /dev/null +++ b/sendgrid/sendgrid.d.ts @@ -0,0 +1,169 @@ +// Type definitions for sendgrid 1.1.0 +// Project: https://github.com/sendgrid/sendgrid-nodejs +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Sendgrid { + //#region Options + + export interface UriParts { + protocol: string; + host: string; + port: string; + endpoint: string; + } + + export interface Options { + protocol?: string; + host?: string; + port?: string; + endpoint?: string; + uri?: string; + proxy?: string; + web?: { + pool?: any; + } + } + + export interface OptionsExport { + uriParts: UriParts; + uri: string; + + proxy?: string; + web?: { + pool?: any; + } + } + + //#endregion + + //#region Email + + export interface EmailOptions { + to?: any; + toname?: string; + from?: string; + fromname?: string; + subject?: string; + text?: string; + html?: string; + bcc?: any; + replyto?: string; + date?: Date; + headers?: { [key: string]: string }; + files?: FileHandlerOptions[]; + smtpapi?: any; + } + + export class Email { + to: any; + toname: string; + from: string; + fromname: string; + subject: string; + text: string; + html: string; + bcc: any; + replyto: string; + date: Date; + headers: { [key: string]: string }; + files: FileHandler[]; + smtpapi: any; + + constructor(); + constructor(options: EmailOptions); + + addTo(address: string): void; + addHeader(type: string, value: string): void; + addSubstitution(type: string, value: string): void; + addSubstitution(type: string, value: string[]): void; + addSection(section: { [key: string]: string }): void; + addUniqueArg(uarg: { [key: string]: string }): void; + addCategory(category: string): void; + addFilter(filter: string, command: string, value: number): void; + addFilter(filter: string, command: string, value: string): void; + addFile(file: FileHandlerOptions): void; + + setFrom(address: string): void; + setSubject(subject: string): void; + setText(text: string): void; + setHtml(html: string): void; + setHeaders(headers: { [key: string]: string }): void; + setSubstitutions(substitutions: { [key: string]: string[] }): void; + setSections(sections: { [key: string]: string }): void; + setUniqueArgs(uargs: { [key: string]: string }): void; + setCategories(categories: string[]): void; + setFilters(filters: any): void; + } + + //#endregion + + //#region FileHandler + + export interface FileHandlerOptions { + filename?: string; + contentType?: string; + cid?: string; + path?: string; + url?: string; + content?: any; + } + + export class FileHandler { + filename: string; + contentType: string; + cid: string; + + type: string; + content: string; + path: string; + url: string; + + constructor(options: FileHandlerOptions); + + loadContent(callback: HandlerCallback): void; + + static handlers: { + content: Handler; + path: Handler; + url: Handler; + none: Handler; + }; + } + + export interface Handler { + (file: FileHandler, callback: HandlerCallback): void; + } + + export interface HandlerCallback { + (hasError: boolean, error: Error): void; + (hasError: boolean, error: string): void; + } + + //#endregion + + //#region Sendgrid Class + + interface Constructor { + (api_user: string, api_key: string, options?: Options): Instance; + new (api_user: string, api_key: string, options?: Options): Instance; + } + + export interface Instance { + version: string; + api_user: string; + api_key: string; + options: OptionsExport; + Email: typeof Email; + + send(email: EmailOptions, callback: (err: Error, json: any) => any): void; + send(email: Email, callback: (err: Error, json: any) => any): void; + } + + //#endregion +} + +declare module "sendgrid" { + var ctor: Sendgrid.Constructor; + export = ctor; +} \ No newline at end of file diff --git a/sinon-chai/sinon-chai-tests.ts b/sinon-chai/sinon-chai-tests.ts index b250b142d..48ac47ee9 100644 --- a/sinon-chai/sinon-chai-tests.ts +++ b/sinon-chai/sinon-chai-tests.ts @@ -3,12 +3,17 @@ declare var expect: chai.ExpectStatic; +import chai = require('chai'); +import sinonChai = require('sinon-chai'); + +chai.use(sinonChai); + function test() { var spy: Function; var anotherSpy: Function; - var context; - var match; - + var context: any; + var match: any; + expect(spy).to.have.been.called; expect(spy).to.have.been.calledOnce; expect(spy).to.have.been.calledTwice; diff --git a/sinon-chai/sinon-chai.d.ts b/sinon-chai/sinon-chai.d.ts index f8166d4d6..0f639abb7 100644 --- a/sinon-chai/sinon-chai.d.ts +++ b/sinon-chai/sinon-chai.d.ts @@ -26,3 +26,8 @@ declare module chai { always: Expect; } } + +declare module "sinon-chai" { + function exports(_chai: typeof chai, utils: any): void; + export = exports; +} diff --git a/stampit/stampit-tests.ts b/stampit/stampit-tests.ts new file mode 100644 index 000000000..4354461b7 --- /dev/null +++ b/stampit/stampit-tests.ts @@ -0,0 +1,168 @@ +/// + +var a = stampit().enclose(() => { + var a = 'a'; + this.getA = () => { + return a; + }; +}); +a(); // Object -- so far so good. +a().getA(); // "a" + + +var b = stampit().enclose(function () { + var a = 'b'; + this.getB = function () { + return a; + }; +}); + + +var c = stampit.compose(a, b); +var foo = c(); // we won't throw this one away... +foo.getA(); // "a" +foo.getB(); // "b" + + +// Some more privileged methods, with some private data. +// Use stampit.mixIn() to make this feel declarative: +var availability = stampit().enclose(function () { + var isOpen = false; // private + + return stampit.mixIn(this, { + open: function open() { + isOpen = true; + return this; + }, + close: function close() { + isOpen = false; + return this; + }, + isOpen: function isOpenMethod() { + return isOpen; + } + }); +}); +// Hre's a mixin with public methods, and some state: +var membership = stampit({ + members: {}, + add: function (member: any) { + this.members[member.name] = member; + return this; + }, + getMember: function (name: any) { + return this.members[name]; + } + }, + { + members: {} + }); +// Let's set some defaults: +var defaults = stampit().state({ + name: 'The Saloon', + specials: 'Whisky, Gin, Tequila' +}); + +// Classical inheritance has nothing on this. No parent/child coupling. No deep inheritance hierarchies. +// Just good, clean code reusability. +var bar = stampit.compose(defaults, availability, membership); +// Note that you can override state on instantiation: +var myBar = bar({name: 'Moe\'s'}); +// Silly, but proves that everything is as it should be. +myBar.add({name: 'Homer' }).open().getMember('Homer'); + + + +var myStamp = stampit().methods({ + foo: function () { + return 'foo'; + }, + methodOverride: function () { + return false; + } +}).methods({ + bar: function () { + return 'bar' + }, + methodOverride: function () { + return true; + } +}); + +myStamp.state({ + foo: {bar: 'bar'}, + stateOverride: false +}).state({ + bar: 'bar', + stateOverride: true +}); + +myStamp.enclose(function () { + var secret = 'foo'; + + this.getSecret = function () { + return secret; + }; +}).enclose(function () { + this.a = true; +}).enclose({ + bar: function bar() { + this.b = true; + } +}, { + baz: function baz() { + this.c = true; + } +}); + +var obj = myStamp.create(); +obj.getSecret && obj.a && obj.b && obj.c; // true + +var newStamp = stampit(null, { defaultNum: 1 }).compose(myStamp); + + + +var obj1 = stampit().methods({ + a: function () { return 'a'; } +}, { + b: function () { return 'b'; } +}).create(); + +var obj2 = stampit().state({ + a: 'a' +}, { + b: 'b' +}).create(); + +var obj = defaults.compose(newStamp, membership, availability).create(); + + + +// The old constructor / class thing... +var Constructor = function Constructor() { + this.thing = 'initialized'; +}; +Constructor.prototype.foo = function foo() { return 'foo'; }; + +// The conversion +var oldskool = stampit.convertConstructor(Constructor); + +// A new stamp to compose with... +var newskool = stampit().methods({ + bar: function bar() { return 'bar'; } + // your methods here... +}).enclose(function () { + this.baz = 'baz'; +}); + +// Now you can compose those old constructors just like you could +// with any other stamp... +var myThing = stampit.compose(oldskool, newskool); + +var t = myThing(); + +t.thing; // 'initialized', + +t.foo(); // 'foo', + +t.bar(); // 'bar' \ No newline at end of file diff --git a/stampit/stampit.d.ts b/stampit/stampit.d.ts new file mode 100644 index 000000000..8d46e7477 --- /dev/null +++ b/stampit/stampit.d.ts @@ -0,0 +1,155 @@ +// Type definitions for stampit +// Project: https://github.com/ericelliott/stampit +// Definitions by: Vasyl Boroviak +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var stampit: stampit.Stampit; + +declare module stampit { + interface Stampit { + /** + * Return a factory (akaStamp) function that will produce new objects using the + * prototypes that are passed in or composed. + * @param methods A map of method names and bodies for delegation. + * @param state A map of property names and values to clone for each new object. + * @param enclose A closure (function) used to create private data and privileged methods. + * */ + (methods?:{}, state?:{}, enclose?:{(...encloseArgs:any[]): void}[]):stampit.Stamp; + + /** + * Take two or more Stamps and combine them to produce a new Stamp. + * Combining overrides properties with last-in priority. + * @param stamps Stamps produced by stampit. + * @return A new Stamp made of all the given. + */ + compose(...stamps:Stamp[]): Stamp; + + /** + * Take a destination object followed by one or more source objects, + * and copy the source object properties to the destination object, + * with last in priority overrides. + * @param destination An object to copy properties to. + * @param source Objects to copy properties from. + * @return The destination object. + */ + mixIn(destination:any, ...source:any[]): any; + + /** + * Alias for mixIn. + * Take a destination object followed by one or more source objects, + * and copy the source object properties to the destination object, + * with last in priority overrides. + * @param destination An object to copy properties to. + * @param source Objects to copy properties from. + * @return The destination object. + */ + extend(destination:any, ...source:any[]): any; + + /** + * Check if an object is a Stamp. + * @param obj An object to check. + * @return true if the object is a Stamp; otherwise - false. + */ + isStamp(obj:any): boolean; + + /** + * Take an old-fashioned JS constructor and return a Stamp + * that you can freely compose with other Stamps. + * @param Constructor Old-fashioned constructor function. + * @return A new Stamp based on the given constructor. + */ + convertConstructor(Constructor:any): Stamp; + } + + /** + * A factory function that will produce new objects using the + * prototypes that are passed in or composed. + */ + export interface Stamp { + /** + * Just like calling stamp() invokes the stamp and returns a new object instance. + * @param state Properties you wish to set on the new objects. + * @param encloseArgs The remaining arguments are passed to all .enclose() functions. + * WARNING Avoid using two different .enclose() functions that expect different arguments. + * .enclose() functions that take arguments should not be considered safe to compose + * with other .enclose() functions that also take arguments. Taking arguments with + * an .enclose() function is an anti-pattern that should be avoided, when possible. + * @return A new object composed of the Stamps and prototypes provided. + */ + (state?:{}, ...encloseArgs:any[]): any; + + /** + * Just like calling stamp(), stamp.create() invokes the stamp and returns a new instance. + * @param state Properties you wish to set on the new objects. + * @param encloseArgs The remaining arguments are passed to all .enclose() functions. + * WARNING Avoid using two different .enclose() functions that expect different arguments. + * .enclose() functions that take arguments should not be considered safe to compose + * with other .enclose() functions that also take arguments. Taking arguments with + * an .enclose() function is an anti-pattern that should be avoided, when possible. + * @return A new object composed of the Stamps and prototypes provided. + */ + create(state?:{}, ...encloseArgs:any[]): any; + + /** + * An object map containing the fixed prototypes. + */ + fixed: Fixed; + + /** + * Add methods to the methods prototype. Chainable. + * @param methods Object(s) containing map of method names and bodies for delegation. + * @return Self. + */ + methods(...methods:{}[]): Stamp; + + /** + * Take n objects and add them to the state prototype. Changes `this` object. Chainable. + * @param states Object(s) containing map of property names and values to clone for each new object. + * @return Self. + */ + state(...states:{}[]): Stamp; + + /** + * Take n functions, an array of functions, or n objects and add the functions to the enclose prototype. + * Functions passed into .enclose() are called any time an object is instantiated. + * That happens when the stamp function is invoked, or when the .create() method is called. + * Changes `this` object. Chainable. + * @param functions Closures (functions) used to create private data and privileged methods. + * @return Self. + */ + enclose(...functions:{(...encloseArgs:any[]): void}[]): Stamp; + + /** + * Take n functions, an array of functions, or n objects and add the functions to the enclose prototype. + * Functions passed into .enclose() are called any time an object is instantiated. + * That happens when the stamp function is invoked, or when the .create() method is called. + * Changes `this` object. Chainable. + * @param methods Function properties of these objects will be treated as closure functions. + * @return Self. + */ + enclose(...methods:{}[]): Stamp; + + /** + * Take one or more Stamps and + * combine them with `this` to produce and return a new Stamp. + * Combining overrides properties with last-in priority. + * NOT chainable. + * @param stamps Stampit factories, aka Stamps. + * @return A new Stamp composed from arguments and `this`. + */ + compose(...stamps:Stamp[]): Stamp; + } + + /** + * An object map containing the fixed prototypes. + */ + interface Fixed { + methods: {}; + state: {}; + enclose: {(...encloseArgs:any[]): void}[]; + } +} + +declare module "stampit" { + export = stampit; +} \ No newline at end of file diff --git a/stylus/stylus-tests.ts b/stylus/stylus-tests.ts new file mode 100644 index 000000000..78b2456df --- /dev/null +++ b/stylus/stylus-tests.ts @@ -0,0 +1,104 @@ +/** + * Test suite created by Maxime LUCE + * + * Created by using code samples from https://github.com/LearnBoost/stylus/blob/master/docs/js.md. + */ + +/// +/// +/// + +import stylus = require("stylus"); + +var str = "This is a stylus test"; + +/** + * Basic Usage + */ +stylus.render(str, { filename: 'nesting.css' }, function(err, css){ + if (err) throw err; + console.log(css); +}); + +stylus(str) + .set('filename', 'nesting.css') + .render(function (err, css) { + // logic + }); + +/** + * .set(setting, value) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#setsetting-value + */ +stylus(str) + .set('filename', __dirname + '/test.styl') + .set('paths', [__dirname, __dirname + '/mixins']) + .render(function (err, css) { + // logic + }); + +/** + * .include(path) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#includepath + */ +stylus(str) + .include(require('nib').path) + .include(process.env.HOME + '/mixins') + .render(function (err, css) { + // logic + }); + +/** + * .import(path) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#importpath + */ +stylus(str) + .set('filename', __dirname + '/test.styl') + .import('mixins/vendor') + .render(function (err, css) { + if (err) throw err; + console.log(css); + }); + +/** + * .define(name, node|fn) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#definename-node + */ +stylus(str) + .define('has-canvas', stylus.nodes.false) + .define('some-setting', new stylus.nodes.String('some value')) + + .define('string', 'some string') + .define('number', 15.5) + .define('some-bool', true) + .define('list', [1, 2, 3]) + .define('list', [1, 2, [3, 4, [5, 6]]]) + .define('list', { foo: 'bar', bar: 'baz' }) + .define('families', ['Helvetica Neue', 'Helvetica', 'sans-serif']) + + .define('get-list', function () { + return ['foo', 'bar', 'baz']; + }) + + .render(function (err, css) { + if (err) throw err; + console.log(css); + }); + +/** + * .use(fn) + * https://github.com/LearnBoost/stylus/blob/master/docs/js.md#usefn + */ +var mylib = function (style: Stylus.Renderer) { + style.define('number', 15.5); + style.define('get-list', function () { + return ['foo', 'bar', 'baz']; + }); +}; + +stylus(str) + .use(mylib) + .render(function (err, css) { + if (err) throw err; + console.log(css); + }); diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts new file mode 100644 index 000000000..d6fd6ef5b --- /dev/null +++ b/stylus/stylus.d.ts @@ -0,0 +1,1439 @@ +// Type definitions for stylus 0.48.1 +// Project: https://github.com/LearnBoost/stylus +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Stylus { + + export interface Static { + /** + * Return a new `Renderer` for the given `str` and `options`. + */ + (str: string): Renderer; + (str: string, options: RenderOptions): Renderer; + + /** + * Library version. + */ + version: string; + + /** + * Expose nodes. + */ + nodes: NodeStatic; + + /** + * Expose BIFs. + */ + functions: Functions; + + /** + * Expose utils. + */ + utils: Utils; + + Visitor: typeof Visitor; + Parser: typeof Parser; + Evaluator: typeof Evaluator; + Compiler: typeof Compiler; + + /** + * Expose middleware. + */ + middleware(dir: string): Middleware; + + /** + * Convert the given `css` to `stylus` source. + */ + convertCSS(css: string): string; + + /** + * Render the given `str` with `options` and callback `fn(err, css)`. + */ + render(str: string, callback: RenderCallback): void; + render(str: string, options: RenderOptions, callback: RenderCallback): void; + + /** + * Return a url() function with the given `options`. + */ + url: UrlFunction; + + /** + * Return a url() function with the given `options`. + */ + resolver(options: any): LiteralFunction; + } + + //#region Internal Modules + + export interface NodeStatic { + Node: typeof Nodes.Node; + Root: typeof Nodes.Root; + Null: typeof Nodes.Null; + Each: typeof Nodes.Each; + If: typeof Nodes.If; + Call: typeof Nodes.Call; + UnaryOp: typeof Nodes.UnaryOp; + BinOp: typeof Nodes.BinOp; + Ternary: typeof Nodes.Ternary; + Block: typeof Nodes.Block; + Unit: typeof Nodes.Unit; + String: typeof Nodes.String; + HSLA: typeof Nodes.HSLA; + RGBA: typeof Nodes.RGBA; + Ident: typeof Nodes.Ident; + Group: typeof Nodes.Group; + Literal: typeof Nodes.Literal; + Boolean: typeof Nodes.Boolean; + Return: typeof Nodes.Return; + Media: typeof Nodes.Media; + QueryList: typeof Nodes.QueryList; + Query: typeof Nodes.Query; + QueryExpr: typeof Nodes.QueryExpr; + Params: typeof Nodes.Params; + Comment: typeof Nodes.Comment; + Keyframes: typeof Nodes.Keyframes; + Member: typeof Nodes.Member; + Charset: typeof Nodes.Charset; + Namespace: typeof Nodes.Namespace; + Import: typeof Nodes.Import; + Extend: typeof Nodes.Extend; + Object: typeof Nodes.Object; + Function: typeof Nodes.Function; + Property: typeof Nodes.Property; + Selector: typeof Nodes.Selector; + Expression: typeof Nodes.Expression; + Arguments: typeof Nodes.Arguments; + Atblock: typeof Nodes.Atblock; + Atrule: typeof Nodes.Atrule; + + true: Nodes.Boolean; + false: Nodes.Boolean; + null: Nodes.Null; + } + + export interface Functions { + /** + * Convert the given `color` to an `HSLA` node, + * or h,s,l,a component values. + */ + hsla(rgba: Nodes.RGBA): Nodes.HSLA; + hsla(hsla: Nodes.HSLA): Nodes.HSLA; + hsla(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit, alpha: Nodes.Unit): Nodes.HSLA; + + /** + * Convert the given `color` to an `HSLA` node, + * or h,s,l component values. + */ + hsl(rgba: Nodes.RGBA): Nodes.HSLA; + hsl(hsla: Nodes.HSLA): Nodes.HSLA; + hsl(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit): Nodes.HSLA; + + /** + * Return type of `node`. + */ + type(node: Nodes.Node): string; + /** + * Return type of `node`. + */ + typeof(node: Nodes.Node): string; + /** + * Return type of `node`. + */ + "type-of"(node: Nodes.Node): string; + + /** + * Return component `name` for the given `color`. + */ + component(color: Nodes.RGBA, name: Nodes.String): Nodes.Unit; + component(color: Nodes.HSLA, name: Nodes.String): Nodes.Unit; + + /** + * Return component `name` for the given `color`. + */ + basename(path: Nodes.String): string; + basename(path: Nodes.String, ext: Nodes.String): string; + + /** + * Return the dirname of `path`. + */ + dirname(path: Nodes.String): string; + + /** + * Return the extension of `path`. + */ + extname(path: Nodes.String): string; + + /** + * Joins given paths + */ + pathjoin(...paths: Nodes.String[]): string; + + /** + * Return the red component of the given `color`, + * or set the red component to the optional second `value` argument. + */ + red(color: Nodes.RGBA): Nodes.Unit; + red(color: Nodes.HSLA): Nodes.Unit; + red(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + red(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the green component of the given `color`, + * or set the green component to the optional second `value` argument. + */ + green(color: Nodes.RGBA): Nodes.Unit; + green(color: Nodes.HSLA): Nodes.Unit; + green(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + green(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the blue component of the given `color`, + * or set the blue component to the optional second `value` argument. + */ + blue(color: Nodes.RGBA): Nodes.Unit; + blue(color: Nodes.HSLA): Nodes.Unit; + blue(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + blue(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the alpha component of the given `color`, + * or set the alpha component to the optional second `value` argument. + */ + alpha(color: Nodes.RGBA): Nodes.Unit; + alpha(color: Nodes.HSLA): Nodes.Unit; + alpha(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + alpha(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the hue component of the given `color`, + * or set the hue component to the optional second `value` argument. + */ + hue(color: Nodes.RGBA): Nodes.Unit; + hue(color: Nodes.HSLA): Nodes.Unit; + hue(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + hue(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the saturation component of the given `color`, + * or set the saturation component to the optional second `value` argument. + */ + saturation(color: Nodes.RGBA): Nodes.Unit; + saturation(color: Nodes.HSLA): Nodes.Unit; + saturation(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + saturation(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return the lightness component of the given `color`, + * or set the lightness component to the optional second `value` argument. + */ + lightness(color: Nodes.RGBA): Nodes.Unit; + lightness(color: Nodes.HSLA): Nodes.Unit; + lightness(color: Nodes.RGBA, value: Nodes.Unit): Nodes.RGBA; + lightness(color: Nodes.HSLA, value: Nodes.Unit): Nodes.RGBA; + + /** + * Return a `RGBA` from the r,g,b,a channels. + */ + rgba(rgba: Nodes.RGBA): Nodes.RGBA; + rgba(hsla: Nodes.HSLA): Nodes.RGBA; + rgba(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit, alpha: Nodes.Unit): Nodes.RGBA; + + /** + * Return a `RGBA` from the r,g,b channels. + */ + rgb(rgba: Nodes.RGBA): Nodes.RGBA; + rgb(hsla: Nodes.HSLA): Nodes.RGBA; + rgb(hue: Nodes.Unit, saturation: Nodes.Unit, lightness: Nodes.Unit, alpha: Nodes.Unit): Nodes.RGBA; + + /** + * Blend the `top` color over the `bottom` + */ + blend(top: Nodes.RGBA): Nodes.RGBA; + blend(top: Nodes.RGBA, bottom: Nodes.RGBA): Nodes.RGBA; + blend(top: Nodes.RGBA, bottom: Nodes.HSLA): Nodes.RGBA; + blend(top: Nodes.HSLA): Nodes.RGBA; + blend(top: Nodes.HSLA, bottom: Nodes.RGBA): Nodes.RGBA; + blend(top: Nodes.HSLA, bottom: Nodes.HSLA): Nodes.RGBA; + + /** + * Returns the relative luminance of the given `color`, + * see http://www.w3.org/TR/WCAG20/#relativeluminancedef + */ + luminosity(rgba: Nodes.RGBA): Nodes.Unit; + luminosity(rgba: Nodes.HSLA): Nodes.Unit; + + /** + * Returns the contrast ratio object between `top` and `bottom` colors, + * based on http://leaverou.github.io/contrast-ratio/ + * and https://github.com/LeaVerou/contrast-ratio/blob/gh-pages/color.js#L108 + */ + contrast(top: Nodes.RGBA): Nodes.Object; + contrast(top: Nodes.RGBA, bottom: Nodes.RGBA): Nodes.Object; + contrast(top: Nodes.RGBA, bottom: Nodes.HSLA): Nodes.Object; + contrast(top: Nodes.HSLA): Nodes.Object; + contrast(top: Nodes.HSLA, bottom: Nodes.RGBA): Nodes.Object; + contrast(top: Nodes.HSLA, bottom: Nodes.HSLA): Nodes.Object; + + /** + * Returns the transparent version of the given `top` color, + * as if it was blend over the given `bottom` color. + */ + transparentify(top: Nodes.RGBA): Nodes.Object; + transparentify(top: Nodes.RGBA, bottom: Nodes.RGBA, alpha?: Nodes.Unit): Nodes.Object; + transparentify(top: Nodes.RGBA, bottom: Nodes.HSLA, alpha?: Nodes.Unit): Nodes.Object; + transparentify(top: Nodes.HSLA): Nodes.Object; + transparentify(top: Nodes.HSLA, bottom: Nodes.RGBA, alpha?: Nodes.Unit): Nodes.Object; + transparentify(top: Nodes.HSLA, bottom: Nodes.HSLA, alpha?: Nodes.Unit): Nodes.Object; + + /** + * Convert a .json file into stylus variables or object. + * Nested variable object keys are joined with a dash (-) + * + * Given this sample media-queries.json file: + * { + * "small": "screen and (max-width:400px)", + * "tablet": { + * "landscape": "screen and (min-width:600px) and (orientation:landscape)", + * "portrait": "screen and (min-width:600px) and (orientation:portrait)" + * } + * } + */ + json(path: Nodes.String, local: Nodes.Boolean, namePrefix: Nodes.String): any; + + /** + * Use the given `plugin`. + */ + use(plugin: Nodes.String): void; + use(plugin: Nodes.String, options: any): void; + + /** + * Unquote the given `string`. + */ + unquote(str: Nodes.String): Nodes.Literal; + + /** + * Like `unquote` but tries to convert the given `str` to a Stylus node. + */ + convert(str: Nodes.String): Nodes.Node; + + /** + * Assign `type` to the given `unit` or return `unit`'s type. + */ + unit(unit: Nodes.Unit, type: Nodes.String): Nodes.Unit; + + /** + * Lookup variable `name` or return Null. + */ + lookup(name: Nodes.String): Nodes.Node; + + /** + * Set a variable `name` on current scope. + */ + define(name: Nodes.String, expr: Nodes.Expression): Nodes.Node; + + /** + * Perform `op` on the `left` and `right` operands. + */ + operate(op: Nodes.String, left: Nodes.Node, right: Nodes.Node): Nodes.Node; + + /** + * Test if `val` matches the given `pattern`. + */ + match(pattern: Nodes.String, val: Nodes.String): Nodes.Boolean; + match(pattern: Nodes.String, val: Nodes.Ident): Nodes.Boolean; + + /** + * Returns substring of the given `val`. + */ + substr(val: Nodes.String, start: Nodes.Number, length: Nodes.Number): Nodes.String; + substr(val: Nodes.Ident, start: Nodes.Number, length: Nodes.Number): Nodes.Ident; + + /** + * Returns string with all matches of `pattern` replaced by `replacement` in given `val` + */ + replace(pattern: Nodes.String, replacement: Nodes.String, val: Nodes.String): Nodes.String; + replace(pattern: Nodes.String, replacement: Nodes.String, val: Nodes.Ident): Nodes.Ident; + + /** + * Splits the given `val` by `delim` + */ + split(pattern: Nodes.String, val: Nodes.String): Nodes.Expression; + split(pattern: Nodes.String, val: Nodes.Ident): Nodes.Expression; + + /** + * Return length of the given `expr`. + */ + length(expr: Nodes.Expression): Nodes.Unit; + + /** + * Inspect the given `expr`. + */ + length(...expr: Nodes.Expression[]): Nodes.Null; + + /** + * Throw an error with the given `msg`. + */ + error(msg: Nodes.String): void; + + /** + * Warn with the given `msg` prefixed by "Warning: ". + */ + warn(msg: Nodes.String): Nodes.Null; + + /** + * Output stack trace. + */ + trace(): Nodes.Null; + + /** + * Push the given args to `expr`. + */ + push(expr: Nodes.Expression, ...nodes: Nodes.Node[]): Nodes.Unit; + + /** + * Pop a value from `expr`. + */ + pop(expr: Nodes.Expression): Nodes.Node; + + /** + * Unshift the given args to `expr`. + */ + unshift(expr: Nodes.Expression, ...nodes: Nodes.Node[]): Nodes.Unit; + + /** + * Unshift the given args to `expr`.. + */ + prepend(expr: Nodes.Expression, ...nodes: Nodes.Node[]): Nodes.Unit; + + /** + * Shift a value from `expr`. + */ + shift(expr: Nodes.Expression): Nodes.Node; + + /** + * Return a `Literal` with the given `fmt`, and variable number of arguments. + */ + s(fmt: Nodes.String, ...nodes: Nodes.Node[]): Nodes.Literal; + + /** + * Return a `Literal` `num` converted to the provided `base`, padded to `width` + * with zeroes (default width is 2) + */ + "base-convert"(num: Nodes.Number, base: Nodes.Number, width: Nodes.Number): Nodes.Literal; + + /** + * Return the opposites of the given `positions`. + */ + "opposite-position"(positions: Nodes.Expression): Nodes.Expression; + + /** + * Return the width and height of the given `img` path. + */ + "image-size"(img: Nodes.String, ignoreErr: Nodes.Boolean): Nodes.Expression; + + /** + * Return the tangent of the given `angle`. + */ + tan(angle: Nodes.Unit): Nodes.Unit; + + /** + * Return the tangent of the given `angle`. + */ + math(n: Nodes.Unit, fn: Nodes.String): Nodes.Unit; + + /** + * Return the opposites of the given `positions`. + */ + "-math-prop"(prop: Nodes.String): Nodes.Unit; + + /** + * Adjust HSL `color` `prop` by `amount`. + */ + adjust(rgba: Nodes.RGBA, prop: Nodes.String, amount: Nodes.Unit): Nodes.RGBA; + adjust(hsla: Nodes.HSLA, prop: Nodes.String, amount: Nodes.Unit): Nodes.RGBA; + + /** + * Return a clone of the given `expr`. + */ + clone(expr: Nodes.Expression): Nodes.Expression; + + /** + * Add property `name` with the given `expr` to the mixin-able block. + */ + "add-property"(name: Nodes.String, expr: Nodes.Expression): Nodes.Property; + + /** + * Merge the object `dest` with the given args. + */ + merge(dest: Nodes.Object, ...objs: Nodes.Object[]): Nodes.Object; + + /** + * Merge the object `dest` with the given args. + */ + extend(dest: Nodes.Object, ...objs: Nodes.Object[]): Nodes.Object; + + /** + * Return the current selector or compile `sel` selector. + */ + selector(): string; + selector(sel: Nodes.String): string; + + /** + * Prefix css classes in a block + */ + "-prefix-classes"(prefix: Nodes.String, block: Nodes.Block): Nodes.Block; + + /** + * Returns the @media string for the current block + */ + "current-media"(): Nodes.String; + + /** + * Return the separator of the given `list`. + */ + "list-separator"(list: Nodes.Expression): Nodes.String; + } + + export interface Utils { + /** + * Check if `path` looks absolute. + */ + absolute(path: string): boolean; + + /** + * Attempt to lookup `path` within `paths` from tail to head. + * Optionally a path to `ignore` may be passed. + */ + lookup(path: string, paths: string, ignore: string, resolveURL: boolean): string; + + /** + * Attempt to lookup `path` within `paths` from tail to head. + * Optionally a path to `ignore` may be passed. + */ + lookupIndex(path: string, paths: string, filename: string): string[]; + + /** + * Like `utils.lookup` but uses `glob` to find files. + */ + find(path: string, paths: string, ignore: string): string[]; + + /** + * Format the given `err` with the given `options`. + */ + formatException(err: Error, options: ExceptionOptions): Error; + + /** + * Assert that `node` is of the given `type`, or throw. + */ + assertType(node: Nodes.Node, type: string, param: string): void; + + /** + * Assert that `node` is a `String` or `Ident`. + */ + assertString(node: Nodes.Node, param: string): void; + + /** + * Assert that `node` is a `RGBA` or `HSLA`. + */ + assertColor(node: Nodes.Node, param: string): void; + + /** + * Assert that param `name` is given, aka the `node` is passed. + */ + assertPresent(node: Nodes.Node, name: string): void; + + /** + * Unwrap `expr`. + * + * Takes an expressions with length of 1 + * such as `((1 2 3))` and unwraps it to `(1 2 3)`. + */ + unwrap(expr: Nodes.Expression): Nodes.Node; + + /** + * Coerce JavaScript values to their Stylus equivalents. + */ + coerce(val: any): Nodes.Node; + coerce(val: any, raw: boolean): Nodes.Node; + + /** + * Coerce a javascript `Array` to a Stylus `Expression`. + */ + coerceArray(val: any): Nodes.Expression; + coerceArray(val: any, raw: boolean): Nodes.Expression; + + /** + * Coerce a javascript object to a Stylus `Expression` or `Object`. + * + * For example `{ foo: 'bar', bar: 'baz' }` would become + * the expression `(foo 'bar') (bar 'baz')`. If `raw` is true + * given `obj` would become a Stylus hash object. + */ + coerceObject(obj: any): Nodes.Expression; + coerceObject(obj: any, raw: boolean): Nodes.Expression; + + /** + * Return param names for `fn`. + */ + params(fn: Function): string[]; + + /** + * Merge object `b` with `a`. + */ + merge(a: any, b: any): any; + + /** + * Returns an array with unique values. + */ + uniq(arr: any[]): any[]; + + /** + * Compile selector strings in `arr` from the bottom-up + * to produce the selector combinations. For example + * the following Stylus: + */ + compileSelectors(arr: string[], leaveHidden: boolean): string[]; + } + + export interface UrlFunction { + (options: UrlOptions): LiteralFunction; + + mimes: { + ".gif": string; + ".png": string; + ".jpg": string; + ".jpeg": string; + ".svg": string; + ".ttf": string; + ".eot": string; + ".woff": string; + }; + } + + export interface Middleware { + (req: any, res: any, next: Function): void; + } + + //#endregion + + //#region Internal Classes + + export class Visitor { + } + + export class Parser { + } + + export class Evaluator { + } + + export class Compiler { + } + + export class Renderer implements NodeJS.EventEmitter { + options: RenderOptions; + str: string; + events: any; + + constructor(str: string); + constructor(str: string, options: RenderOptions); + + /** + * Parse and evaluate AST, then callback `fn(err, css, js)`. + */ + render(callback: RenderCallback): void; + + /** + * Get dependencies of the compiled file. + */ + deps(filename: string): string[]; + + /** + * Set option `key` to `val`. + */ + set(key: string, val: any): Renderer; + + /** + * Get option `key`. + */ + get(key: string): any; + + /** + * Include the given `path` to the lookup paths array. + */ + include(path: string): Renderer; + + /** + * Use the given `fn`. + * + * This allows for plugins to alter the renderer in + * any way they wish, exposing paths etc. + */ + use(fn: (renderer: Renderer) => any): Renderer; + + /** + * Define function or global var with the given `name`. Optionally + * the function may accept full expressions, by setting `raw` + * to `true`. + */ + define(name: string, fn: Function): Renderer; + define(name: string, node: Nodes.Node): Renderer; + define(name: string, val: any): Renderer; + define(name: string, fn: Function, raw: boolean): Renderer; + define(name: string, node: Nodes.Node, raw: boolean): Renderer; + define(name: string, val: any, raw: boolean): Renderer; + + /** + * Import the given `file`. + */ + import(file: string): Renderer; + + //#region EventEmitter Members + addListener(event: string, listener: Function): Renderer; + on(event: string, listener: Function): Renderer; + once(event: string, listener: Function): Renderer; + removeListener(event: string, listener: Function): Renderer; + removeAllListeners(event?: string): Renderer; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + //#endregion + } + + //#endregion + + //#region Nodes Classes + + export module Nodes { + + export class Node { + lineno: number; + column: number; + filename: string; + + first: Node; + hash: string; + nodeName: string; + + constructor(); + + /** + * Return a clone of this node. + */ + clone(): Node; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { lineno: number; column: number; filename: string }; + + /** + * Nodes by default evaluate to themselves. + */ + eval(): Node; + + /** + * Return true. + */ + toBoolean(): Boolean; + + /** + * Return the expression, or wrap this node in an expression. + */ + toExpression(): Expression; + + /** + * Return false if `op` is generally not coerced. + */ + shouldCoerce(op: string): boolean; + + /** + * Operate on `right` with the given `op`. + */ + operate(op: string, right: Node): Node; + + /** + * Default coercion throws. + */ + coerce(other: Node): Node; + } + + export class Root extends Node { + nodes: Node[]; + + /** + * Push a `node` to this block. + */ + push(node: Node): void; + + /** + * Unshift a `node` to this block. + */ + unshift(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class String extends Node { + val: string; + string: string; + prefixed: boolean; + quote: string; + + constructor(val: string); + constructor(val: string, quote: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { val: string; quote: string; lineno: number; column: number; filename: string }; + } + + export class Number extends Node { + + } + + export class Boolean extends Node { + val: boolean; + isTrue: boolean; + isFalse: boolean; + + constructor(); + constructor(val: boolean); + + /** + * Negate the value. + */ + negate(): Boolean; + + /** + * Return 'Boolean'. + */ + inspect(): Boolean; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: boolean; lineno: number; column: number; filename: string }; + } + + export class Object extends Node { + vals: Dictionary; + length: number; + + constructor(); + + /** + * Set `key` to `val`. + */ + set(key: string, value: Node): Object; + + /** + * Get `key`. + */ + get(key: string): Node; + + /** + * Has `key`? + */ + has(key: string): boolean; + + /** + * Convert object to string with properties. + */ + toBlock(): string; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; vals: Dictionary; lineno: number; column: number; filename: string }; + } + + export class Null extends Node { + isNull: boolean; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; lineno: number; column: number; filename: string }; + } + + export class Ident extends Node { + name: string; + string: string; + val: Node; + mixin: boolean; + + isEmpty: boolean; + + constructor(name: string, val: Node); + constructor(name: string, val: Node, mixin: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; val: Node; mixin: boolean; lineno: number; column: number; filename: string }; + } + + export class Literal extends Node { + val: string; + string: string; + prefixed: boolean; + + constructor(str: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; string: string; val: string; prefixed: boolean; lineno: number; column: number; filename: string }; + } + + export class Unit extends Node { + val: number; + type: string; + + constructor(val: number, type: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: number; type: string; lineno: number; column: number; filename: string }; + } + + export class RGBA extends Node { + r: number; + g: number; + b: number; + a: number; + rgba: RGBA; + hsla: HSLA; + + constructor(r: number, g: number, b: number, a: number); + + /** + * Return an `RGBA` without clamping values. + */ + static withoutClamping(r: number, g: number, b: number, a: number): RGBA; + + /** + * Return a `RGBA` from the given `hsla`. + */ + static fromHSLA(hsla: HSLA): RGBA; + + /** + * Add r,g,b,a to the current component values + */ + add(r: number, g: number, b: number, a: number): RGBA; + + /** + * Subtract r,g,b,a from the current component values + */ + substract(r: number, g: number, b: number, a: number): RGBA; + + /** + * Multiply rgb components by `n`. + */ + multiply(n: number): RGBA; + + /** + * Divide rgb components by `n`. + */ + divide(n: number): RGBA; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; r: number; g: number; b: number; a: number; lineno: number; column: number; filename: string }; + } + + export class HSLA extends Node { + h: number; + s: number; + l: number; + a: number; + hsla: HSLA; + rgba: RGBA; + + constructor(h: number, s: number, l: number, a: number); + + /** + * Return a `HSLA` from the given `hsla`. + */ + static fromRGBA(rgba: RGBA): HSLA; + + /** + * Add h,s,l to the current component values + */ + add(h: number, s: number, l: number): HSLA; + + /** + * Subtract h,s,l from the current component values + */ + substract(h: number, s: number, l: number): HSLA; + + /** + * Adjust lightness by `percent`. + */ + adjustLightness(percent: number): HSLA; + + /** + * djust hue by `deg`. + */ + adjustHue(deg: number): HSLA; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; h: number; s: number; l: number; a: number; lineno: number; column: number; filename: string }; + } + + export class Block extends Node { + nodes: Node[]; + parent: Block; + node: Node; + scope: boolean; + + hasProperties: boolean; + hasMedia: boolean; + isEmpty: boolean; + + constructor(parent: Block); + constructor(parent: Block, node: Node); + + /** + * Push a `node` to this block. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; scope: boolean; lineno: number; column: number; filename: string }; + } + + export class Group extends Node { + nodes: Node[]; + block: Block; + + hasOnlyPlaceholders: boolean; + + constructor(); + + /** + * Push the given `selector` node. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; block: Block; lineno: number; column: number; filename: string }; + } + + export class Expression extends Node { + nodes: Node[]; + isList: boolean; + + isEmpty: boolean; + first: Node; + + constructor(isList: boolean); + + /** + * Push the given node. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; isList: boolean; lineno: number; column: number; filename: string }; + } + + export class Property extends Node { + segments: Node[]; + expr: Expression; + + constructor(segs: Node[], expr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; name: string; expr?: Expression; literal?: Literal; lineno: number; column: number; filename: string }; + } + + export class Each extends Node { + val: string; + key: string; + expr: Expression; + block: Block; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; key: string; expr: Expression; block: Block; lineno: number; column: number; filename: string }; + } + + export class If extends Node { + cond: Expression; + elses: Expression[]; + block: Block; + negate: boolean; + + constructor(cond: Expression, negate: boolean); + constructor(cond: Expression, block: Block); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; cond: Expression; elses: Expression[]; block: Block; negate: boolean; lineno: number; column: number; filename: string }; + } + + export class Call extends Node { + name: string; + args: Expression; + + constructor(name: string, args: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; args: Expression; lineno: number; column: number; filename: string }; + } + + export class UnaryOp extends Node { + op: string; + expr: Expression; + + constructor(op: string, expr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; expr: Expression; lineno: number; column: number; filename: string }; + } + + export class BinOp extends Node { + op: string; + left: Expression; + right: Expression; + + constructor(op: string, left: Expression, right: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; left: Expression; right: Expression; lineno: number; column: number; filename: string }; + } + + export class Ternary extends Node { + op: string; + trueExpr: Expression; + falseExpr: Expression; + + constructor(op: string, trueExpr: Expression, falseExpr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; op: string; trueExpr: Expression; falseExpr: Expression; lineno: number; column: number; filename: string }; + } + + export class Return extends Node { + expr: Expression; + + constructor(expr: Expression); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; expr: Expression; lineno: number; column: number; filename: string }; + } + + export class Media extends Node { + val: string; + + constructor(val: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; + } + + export class QueryList extends Node { + nodes: Node[]; + + constructor(); + + /** + * Push the given `node`. + */ + push(node: Node): void; + + /** + * Merges this query list with the `other`. + */ + merge(other: MediaQueryList): MediaQueryList; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class Query extends Node { + nodes: QueryExpr[]; + type: string; + predicate: string; + + resolvedType: string; + resolvedPredicate: string; + + constructor(); + + /** + * Push the given `expr`. + */ + push(expr: QueryExpr): void; + + /** + * Merges this query with the `other`. + */ + merge(other: Query): Query; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: QueryExpr[]; predicate: string; type: string; lineno: number; column: number; filename: string }; + } + + export class QueryExpr extends Node { + segments: Node[]; + expr: Expression; + + constructor(segs: Node[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; lineno: number; column: number; filename: string }; + } + + export class Params extends Node { + nodes: Node[]; + + length: number; + + /** + * Push the given `node`. + */ + push(node: Node): void; + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class Comment extends Node { + str: string; + suppress: boolean; + inline: boolean; + + constructor(str: string, suppress: boolean, inline: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; str: string; suppress: boolean; inline: boolean; lineno: number; column: number; filename: string }; + } + + export class Keyframes extends Node { + segments: Node[]; + prefix: string; + + constructor(segs: Node[]); + constructor(segs: Node[], prefix: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; prefix: string; block: Block; lineno: number; column: number; filename: string }; + } + + export class Member extends Node { + left: Node; + right: Node; + + constructor(left: Node, right: Node); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; left: Node; right: Node; val?: string; lineno: number; column: number; filename: string }; + } + + export class Charset extends Node { + val: string; + + constructor(val: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; lineno: number; column: number; filename: string }; + } + + export class Namespace extends Node { + val: string; + prefix: string; + + constructor(val: string, prefix: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; val: string; prefix: string; lineno: number; column: number; filename: string }; + } + + export class Import extends Node { + path: Expression; + once: boolean; + + constructor(path: Expression); + constructor(path: Expression, once: boolean); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; path: Expression; lineno: number; column: number; filename: string }; + } + + export class Extend extends Node { + selectors: Selector[]; + + constructor(selectors: Selector[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; selectors: Selector[]; lineno: number; column: number; filename: string }; + } + + export class Function extends Node { + name: string; + params: Params; + body: Block; + + constructor(name: string, params: Params, body: Block); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; name: string; params: Params; body: Block; lineno: number; column: number; filename: string }; + } + + export class Selector extends Node { + inherits: boolean; + segments: Node[]; + + constructor(segs: Node[]); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; segments: Node[]; inherits: boolean; val: string; lineno: number; column: number; filename: string }; + } + + export class Arguments extends Expression { + map: Dictionary; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; map: Dictionary; isList: boolean; preserve: boolean; nodes: Node[]; lineno: number; column: number; filename: string }; + } + + export class Atblock extends Node { + block: Block; + nodes: Node[]; + + constructor(); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; block: Block; lineno: number; column: number; filename: string }; + } + + export class Atrule extends Node { + type: string; + + hasOnlyProperties: boolean; + + constructor(type: string); + + /** + * Return a JSON representation of this node. + */ + toJSON(): { __type: string; type: string; segments: Node[]; block?: Block; lineno: number; column: number; filename: string }; + } + } + + //#endregion + + //#region Internal Interfaces + + export interface Dictionary { + [key: string]: T; + } + + export interface RenderOptions { + globals?: Dictionary; + functions?: Dictionary; + imports?: string[]; + paths?: string[]; + filename?: string; + Evaluator?: typeof Evaluator; + } + + export interface RenderCallback { + (err: Error, css: string, js: string): void; + } + + export interface UrlOptions { + limit?: string; + path: string; + } + + export interface LiteralFunction { + (url: string): Nodes.Literal; + raw: boolean; + } + + export interface ExceptionOptions { + filename: string; + context: number; + lineno: number; + column: number; + input: string; + } + + //#endregion +} + +declare module "stylus" { + var stylus: Stylus.Static; + export = stylus; +} diff --git a/swig/swig-tests.ts b/swig/swig-tests.ts index 1f68aa44c..929a67c89 100644 --- a/swig/swig-tests.ts +++ b/swig/swig-tests.ts @@ -2,24 +2,61 @@ import swig = require('swig'); +var swigObj: swig.Swig; var value: any; var str: string; var num: number; var bool: boolean; -var opts: swig.Options = { - allowErrors: bool, - autoescape: bool, - cache: bool, - encoding: str, - filters: value, - root: str, - tags: value, - extensions: value, - tzOffset: num +function replaceMs(input:string): string { + return input.replace(/m/g, 'f'); +} + +var opts: swig.SwigOptions = { + autoescape: bool, + cache: value, + cmtControls: ["", ""], + loader: swig.loaders.fs(), + locals: { testVal: "my test" }, + tagControls: ["", ""], + varControls: ["", ""] }; -swig.init(opts); -value = swig.compileFile(str); -value = swig.compile(str); -value = swig.compile(str, opts); +swig.setDefaults(opts); +swig.setDefaultTZOffset(num); +swigObj = new swig.Swig(opts); +str = swig.compileFile(str)(); +swig.compileFile(str, {}, function (err: Error, render: (locals: any) => string) { + str = render({}); +}); +str = swig.compile(str)(); +str = swig.compile(str, opts)(); +swig.invalidateCache(); +swig.setFilter("replaceMs", replaceMs); +swig.setTag('tacos', function (): boolean { return true; }, function (): string { return 'Tacos' }, true, true); +swig.setExtension("test", function (v: string) { return 'test: ' + v }); +value = swig.precompile(str, opts); +str = swig.render(str, opts); +str = swig.renderFile(str, {}); +swig.renderFile(str, {}, function (err: Error, output: string) { + +}); +console.log(swig.version); + + +str = swigObj.compileFile(str)(); +swigObj.compileFile(str, opts, function (err: Error, render: (locals: any) => string) { + str = render({}); +}); +str = swigObj.compile(str)(); +str = swigObj.compile(str, opts)(); +swigObj.invalidateCache(); +swigObj.setFilter("replaceMs", replaceMs); +swigObj.setTag('tacos', function (): boolean { return true; }, function (): string { return 'Tacos' }, true, true); +swigObj.setExtension("test", function (v: string) { return 'test: ' + v }); +value = swigObj.precompile(str, opts); +str = swigObj.render(str, opts); +str = swigObj.renderFile(str, {}); +swigObj.renderFile(str, {}, function (err: Error, output: string) { + +}); \ No newline at end of file diff --git a/swig/swig.d.ts b/swig/swig.d.ts index 4d8bc9ebe..4f2b22123 100644 --- a/swig/swig.d.ts +++ b/swig/swig.d.ts @@ -1,27 +1,158 @@ // Type definitions for swig // Project: http://github.com/paularmstrong/swig -// Definitions by: Carlos Ballesteros Velasco +// Definitions by: Peter Harris , Carlos Ballesteros Velasco // Definitions: https://github.com/borisyankov/DefinitelyTyped -// Imported from: https://github.com/soywiz/typescript-node-definitions/swig.d.ts - // API Documentation : http://paularmstrong.github.io/swig/docs/api/ declare module "swig" { - export function init(options: Options): void; - export function compileFile(filepath: string): any; - export function compile(source: string, options?: Options): any; - export function renderFile(pathName: string, locals?: any, cb?: (err: any, output: string) => void): string; + export class Swig { + constructor(options?: SwigOptions); - export interface Options { - allowErrors?: boolean; - autoescape?: boolean; - cache?: boolean; - encoding?: string; - filters?: any; - root?: string; - tags?: any; - extensions?: any; - tzOffset?: number; - } -} + setFilter( + name: string, + method: (input: any, ...args: any[]) => string + ): void; + setTag( + name: string, + parse: (str?: string, line?: string, parser?: Object, types?: lexer.TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, + compile: (compiler?: (content?: string, parents?: any, options?: any, blockName?: string) => string, args?: any[], content?: string, parents?: any, options?: any, blockName?: string) => string, + ends?: boolean, + blockLevel?: boolean + ): void; + setExtension(name: string, object: any): void; + parseFile(pathName: string, options?: any): parser.ParseReturn; + precompile(source: string, options?: SwigOptions): any; + compile(source: string, options?: SwigOptions): (locals?: any) => string; + compileFile(pathname: string, options: SwigOptions, cb: (err: Error, compiledRender: (locals?: any) => string) => void): void; + compileFile(pathname: string, options?: SwigOptions): (locals?: any) => string; + render(source: string, options?: SwigOptions): string; + renderFile(pathName: string, locals: any, cb: (err: Error, output: string) => void): void; + renderFile(pathName: string, locals?: any): string + run(templateFn: Function, locals?: any, filePath?: string): string; + invalidateCache(): void; + + loaders: typeof loaders; + } + + export module lexer { + export enum TYPES { + /** Whitespace */ + WHITESPACE = 0, + /** Plain string */ + STRING = 1, + /** Variable filter */ + FILTER = 2, + /** Empty variable filter */ + FILTEREMPTY = 3, + /** Function */ + FUNCTION = 4, + /** Function with no arguments */ + FUNCTIONEMPTY = 5, + /** Open parenthesis */ + PARENOPEN = 6, + /** Close parenthesis */ + PARENCLOSE = 7, + /** Comma */ + COMMA = 8, + /** Variable */ + VAR = 9, + /** Number */ + NUMBER = 10, + /** Math operator */ + OPERATOR = 11, + /** Open square bracket */ + BRACKETOPEN = 12, + /** Close square bracket */ + BRACKETCLOSE = 13, + /** Key on an object using dot-notation */ + DOTKEY = 14, + /** Start of an array */ + ARRAYOPEN = 15, + /** End of an array + * Currently unused + ARRAYCLOSE = 16, */ + /** Open curly brace */ + CURLYOPEN = 17, + /** Close curly brace */ + CURLYCLOSE = 18, + /** Colon (:) */ + COLON = 19, + /** JavaScript-valid comparator */ + COMPARATOR = 20, + /** Boolean logic */ + LOGIC = 21, + /** Boolean logic "not" */ + NOT = 22, + /** true or false */ + BOOL = 23, + /** Variable assignment */ + ASSIGNMENT = 24, + /** Start of a method */ + METHODOPEN = 25, + /** End of a method + * Currently unused + METHODEND = 26, */ + /** Unknown type */ + UNKNOWN = 100 + } + + export function read(str: string): string[]; + } + + export module parser { + interface ParseReturn { + name: string; + parent: any; + tokens: any[]; + blocks: any; + } + } + + export interface SwigOptions { + autoescape?: boolean; + cache?: any; + cmtControls?: string[]; + loader?: TemplateLoader; + locals?: any; + tagControls?: string[]; + varControls?: string[]; + } + + export interface TemplateLoader { + resolve(to: string, from: string): string; + load(identifier: string, callback?: (err: Error, data: any) => void): void; + load(identifier:string): any; + } + + export module loaders { + export function fs(basepath?: string, encoding?: string): TemplateLoader; + export function memory(mapping: any, basepath?: string): TemplateLoader; + } + + export var version: string; + export function setDefaults(options: SwigOptions): void; + export function setDefaultTZOffset(offset: number): void; + export function setFilter( + name: string, + method: (input: any, ...args: any[]) => string + ): void; + export function setTag( + name: string, + parse: (str?: string, line?: string, parser?: Object, types?: lexer.TYPES, stack?: any, opts?: Object, swig?: Swig) => boolean, + compile: (compiler?: (content?: string, parents?: any, options?: any, blockName?: string) => string, args?: any[], content?: string, parents?: any, options?: any, blockName?: string) => string, + ends?: boolean, + blockLevel?: boolean + ): void; + export function setExtension(name: string, object: any): void; + export function parseFile(pathName: string, options?: any): parser.ParseReturn; + export function precompile(source: string, options?: SwigOptions): any; + export function compile(source: string, options?: SwigOptions): (locals?: any) => string; + export function compileFile(pathname: string, options: SwigOptions, cb: (err: Error, compiledRender: (locals?: any) => string) => void): void; + export function compileFile(pathname: string, options?: SwigOptions): (locals?: any) => string; + export function render(source: string, options?: SwigOptions): string; + export function renderFile(pathName: string, locals: any, cb: (err: Error, output: string) => void): void; + export function renderFile(pathName: string, locals?: any): string + export function run(templateFn: Function, locals?: any, filePath?: string): string; + export function invalidateCache(): void; +} \ No newline at end of file diff --git a/tar/tar-tests.ts b/tar/tar-tests.ts new file mode 100644 index 000000000..3a7783d52 --- /dev/null +++ b/tar/tar-tests.ts @@ -0,0 +1,28 @@ +/** +* Test suite created by Maxime LUCE +* +* Created by using code samples from https://github.com/npm/node-tar. +*/ + +/// +/// + +import tar = require("tar"); +import fs = require("fs"); + +/** + * Quick Extract + */ +fs.createReadStream("path/to/file.tar").pipe(tar.Extract("path/to/extract")); + +/** + * Use with events + */ +var readStream = fs.createReadStream("/path/to/file.tar"); +var extract = tar.Extract("/path/to/target"); + +readStream.pipe(extract); + +extract.on("entry", (entry: any) => { + +}); diff --git a/tar/tar.d.ts b/tar/tar.d.ts new file mode 100644 index 000000000..6b25a02a7 --- /dev/null +++ b/tar/tar.d.ts @@ -0,0 +1,209 @@ +// Type definitions for tar v1.0.1 +// Project: https://github.com/npm/node-tar +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "tar" { + import stream = require("stream"); + + //#region Interfaces + + export interface HeaderProperties { + path?: string; + mode?: number; + uid?: number; + gid?: number; + size?: number; + mtime?: number; + uname?: string; + gname?: string; + devmaj?: number; + devmin?: number; + } + + export interface ExtractOptions { + type?: string; + Directory?: boolean; + path?: string; + strip?: number; + } + + export interface ParseStream extends NodeJS.ReadWriteStream { + position: number; + + _stream: stream.Stream; + _ended: boolean; + + _streamEnd(): void; + _process(c: Buffer): void; + _startEntry(c: Buffer): void; + } + + export interface PackStream extends NodeJS.ReadWriteStream { + writable: boolean; + readable: boolean; + + _noProprietary: boolean; + _global: HeaderProperties; + _buffer: stream.Stream[]; + _currentEntry: any; + _processing: boolean; + _pipeRoot: stream.Stream; + _needDrain: boolean; + _paused: boolean; + + addGlobal(props: HeaderProperties): void; + add(stream: stream.Stream): boolean; + destroy(): void; + + _process(): void; + } + + export interface ExtractStream extends ParseStream { + } + + //#endregion + + //#region Enums + + export var fields: { + path: number; + mode: number; + uid: number; + gid: number; + size: number; + mtime: number; + cksum: number; + type: number; + linkpath: number; + ustar: number; + ustarvar: number; + uname: number; + gname: number; + devmaj: number; + devmin: number; + prefix: number; + fill: number; + }; + + export var fieldSize: number[]; + export var fieldOffs: number[]; + export var fieldEnds: number[]; + + /** + * Different values of the 'type' field + * paths match the values of Stats.isX() functions, where appropriate + */ + export var types: { + 0: string; + "\0": string; + "": string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + g: string; + x: string; + A: string; + D: string; + I: string; + K: string; + L: string; + M: string; + N: string; + S: string; + V: string; + X: string; + File: string; + OldFile: string; + Link: string; + SymbolicLick: string; + CharacterDevice: string; + BlockDevice: string; + Directory: string; + FIFO: string; + ContiguousFile: string; + GlobalExtendedHeader: string; + ExtendedHeader: string; + SolarisACL: string; + GNUDumpDir: string; + INode: string; + NextFileHasLonLinkPath: string; + NextFileHasLongPath: string; + ContinuationFile: string; + TapeVolumeHeader: string; + OldExtendedHeader: string; + }; + + /** + * Values for the mode field + */ + export var modes: { + suid: number; + sgid: number; + svtx: number; + uread: number; + uwrite: number; + uexec: number; + gread: number; + gwrite: number; + gexec: number; + oread: number; + owrite: number; + oexec: number; + }; + + export var numeric: { + mode: boolean; + uid: boolean; + gid: boolean; + size: boolean; + mtime: boolean; + devmaj: boolean; + devmin: boolean; + cksum: boolean; + atime: boolean; + ctime: boolean; + dev: boolean; + ino: boolean; + nlink: boolean; + }; + + export var knownExtended: { + atime: boolean; + charset: boolean; + comment: boolean; + ctime: boolean; + gid: boolean; + gname: boolean; + linkpat: boolean; + mtime: boolean; + path: boolean; + realtime: boolean; + security: boolean; + size: boolean; + uid: boolean; + uname: boolean; + }; + + export var headerSize: number; + export var blockSize: number; + + //#endregion + + //#region Global Methods + + export function Parse(): ParseStream; + + export function Pack(props: HeaderProperties): PackStream; + + export function Extract(path: string): ExtractStream; + export function Extract(opts: ExtractOptions): ExtractStream; + + //#endregion +} \ No newline at end of file diff --git a/threejs/three.d.ts b/threejs/three.d.ts index a9c33693c..9408fad57 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -2378,7 +2378,7 @@ declare module THREE { set(min: Vector2, max: Vector2): Box2; setFromPoints(points: Vector2[]): Box2; - setFromCenterAndSize(center: Vector2, size: number): Box2; + setFromCenterAndSize(center: Vector2, size: Vector2): Box2; copy(box: Box2): Box2; makeEmpty(): Box2; empty(): boolean; @@ -2408,7 +2408,7 @@ declare module THREE { set(min: Vector3, max: Vector3): Box3; setFromPoints(points: Vector3[]): Box3; - setFromCenterAndSize(center: Vector3, size: number): Box3; + setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; copy(box: Box3): Box3; makeEmpty(): Box3; @@ -5604,7 +5604,7 @@ declare module THREE { cone: Mesh; setDirection(dir: Vector3): void; - setLength(length: number): void; + setLength(length: number, headLength?: number, headWidth?: number): void; setColor(hex: number): void; } diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index 3c8495f86..bc8d734c3 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -4,7 +4,6 @@ // // Examples from http://twitter.github.com/typeahead.js/examples // -declare var Hogan: string; var substringMatcher = function (strs: any) { return function findMatches(q: any, cb: any) { @@ -24,11 +23,11 @@ var substringMatcher = function (strs: any) { // JavaScript object, refer to typeahead docs for more info matches.push({ value: str }); } -}); + }); cb(matches); - }; -}; + } +} var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', @@ -41,18 +40,234 @@ var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; -$('#the-basics .typeahead').typeahead({ - hint: true, - highlight: true, - minLength: 1 -}, -{ - name: 'states', - displayKey: 'value', - source: substringMatcher(states) -}); -module valueTest { +function test_method_names() { + $('#the-basics .typeahead').typeahead('destroy'); + $('#the-basics .typeahead').typeahead('open'); + $('#the-basics .typeahead').typeahead('close'); + $('#the-basics .typeahead').typeahead('val'); + $('#the-basics .typeahead').typeahead('val', 'test value'); +} + + +function test_options() { + + var dataSets: Twitter.Typeahead.Dataset[] = []; + + function with_empty_options() { + $('#the-basics .typeahead').typeahead({}, dataSets); + } + + function with_hint_option() { + $('#the-basics .typeahead').typeahead({ hint: true }, dataSets); + } + + function with_highlight_option() { + $('#the-basics .typeahead').typeahead({ highlight: true }, dataSets); + } + + function with_minLength_option() { + $('#the-basics .typeahead').typeahead({ minLength: 1 }, dataSets); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead({ + hint: true, + highlight: true, + minLength: 1 + }, + dataSets + ); + } +} + +function test_datasets_array() { + + var options: Twitter.Typeahead.Options = {}; + + function with_only_source() { + $('#the-basics .typeahead').typeahead(options, [{ + source: substringMatcher(states) + }]); + } + + function with_name_option() { + + $('#the-basics .typeahead').typeahead(options, [{ + name: 'states', + source: substringMatcher(states), + }]); + } + + function with_displayKey_option() { + $('#the-basics .typeahead').typeahead(options, [{ + displayKey: 'value', + source: substringMatcher(states) + }] + ); + } + + function with_templates_option() { + $('#the-basics .typeahead').typeahead(options, [{ + templates: {}, + source: substringMatcher(states) + }] + ); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead(options, [{ + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + }] + ); + } + + function with_multiple_datasets() { + $('#the-basics .typeahead').typeahead(options, [ + { + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + }, + { + name: 'states alternative', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + } + ]); + } +} + + +function test_datasets_objects() { + + var options: Twitter.Typeahead.Options = {}; + + function with_only_source() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states) + }); + } + + function with_name_option() { + + $('#the-basics .typeahead').typeahead(options, { + name: 'states', + source: substringMatcher(states), + }); + } + + function with_displayKey_option() { + $('#the-basics .typeahead').typeahead(options, + { + displayKey: 'value', + source: substringMatcher(states) + } + ); + } + + function with_templates_option() { + $('#the-basics .typeahead').typeahead(options, + { + templates: {}, + source: substringMatcher(states) + } + ); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead(options, + { + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + } + ); + } + + function with_multiple_objects() { + $('#the-basics .typeahead').typeahead(options, + { + name: 'states', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + }, + { + name: 'states alternative', + displayKey: 'value', + templates: {}, + source: substringMatcher(states) + } + ); + } +} + +function test_dataset_templates() { + + var options: Twitter.Typeahead.Options = {}; + + function with_no_options() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: {} + }); + } + + function with_empty_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { empty: 'no results' } + }); + } + + function with_footer_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { footer: 'custom footer' } + }); + } + + function with_header_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { header: 'custom header' } + }); + } + + function with_suggestion_option() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { + suggestion: function(context) { + return context.name; + } + } + }); + } + + function with_all_options() { + $('#the-basics .typeahead').typeahead(options, { + source: substringMatcher(states), + templates: { + empty: 'no results', + footer: 'custom footer', + header: 'custom header', + suggestion: function(context) { + return context.name; + } + } + }); + } +} + +function test_value() { var value: string = $('foo').typeahead('val'); $('foo').typeahead('val', value); } \ No newline at end of file diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index f847d3634..28c6b0f3a 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -8,7 +8,7 @@ interface JQuery { /** - * Destroys previously initialized typeaheads. This entails reverting + * Destroys previously initialized typeaheads. This entails reverting * DOM modifications and removing event handlers. * * @constructor @@ -17,7 +17,7 @@ interface JQuery { typeahead(methodName: 'destroy'): JQuery; /** - * Opens the dropdown menu of typeahead. Note that being open does not mean that the menu is visible. + * Opens the dropdown menu of typeahead. Note that being open does not mean that the menu is visible. * The menu is only visible when it is open and has content. * * @constructor @@ -68,7 +68,7 @@ interface JQuery { * @param query The query to be set in case method 'val' is used. */ typeahead(methodName: string, query: string): JQuery; - + /** * Accomodates specifying options such as hint and highlight. * This is in correspondence to the examples mentioned in http://twitter.github.io/typeahead.js/examples/ @@ -92,38 +92,38 @@ interface JQuery { declare module Twitter.Typeahead { /** - * A dataset is an object that defines a set of data that hydrates + * A dataset is an object that defines a set of data that hydrates * suggestions. Typeaheads can be backed by multiple datasets. - * Given a query, a typeahead instance will inspect its backing + * Given a query, a typeahead instance will inspect its backing * datasets and display relevant suggestions to the end-user. */ interface Dataset { /** - * The backing data source for suggestions. - * Expected to be a function with the signature (query, cb). - * It is expected that the function will compute the suggestion set (i.e. an array of JavaScript objects) for query and then invoke cb with said set. - * cb can be invoked synchronously or asynchronously. - * + * The backing data source for suggestions. + * Expected to be a function with the signature (query, cb). + * It is expected that the function will compute the suggestion set (i.e. an array of JavaScript objects) for query and then invoke cb with said set. + * cb can be invoked synchronously or asynchronously. + * */ source: (query: string, cb: (result: any) => void) => void; - /** - * The name of the dataset. - * This will be appended to tt-dataset- to form the class name of the containing DOM element. - * Must only consist of underscores, dashes, letters (a-z), and numbers. + /** + * The name of the dataset. + * This will be appended to tt-dataset- to form the class name of the containing DOM element. + * Must only consist of underscores, dashes, letters (a-z), and numbers. * Defaults to a random number. */ name?: string; /** - * For a given suggestion object, determines the string representation of it. - * This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. + * For a given suggestion object, determines the string representation of it. + * This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. * Defaults to value. */ displayKey?: string; /** - * A hash of templates to be used when rendering the dataset. + * A hash of templates to be used when rendering the dataset. * Note a precompiled template is a function that takes a JavaScript object as its first argument and returns a HTML string. */ templates?: Templates; @@ -133,45 +133,45 @@ declare module Twitter.Typeahead { interface Templates { /** - * Rendered when 0 suggestions are available for the given query. - * Can be either a HTML string or a precompiled template. + * Rendered when 0 suggestions are available for the given query. + * Can be either a HTML string or a precompiled template. * If it's a precompiled template, the passed in context will contain query */ empty?: string; /** * Rendered at the bottom of the dataset. - * Can be either a HTML string or a precompiled template. + * Can be either a HTML string or a precompiled template. * If it's a precompiled template, the passed in context will contain query and isEmpty. */ footer?: string; /** - * Rendered at the top of the dataset. - * Can be either a HTML string or a precompiled template. + * Rendered at the top of the dataset. + * Can be either a HTML string or a precompiled template. * If it's a precompiled template, the passed in context will contain query and isEmpty. */ header?: string; /** - * Used to render a single suggestion. - * If set, this has to be a precompiled template. - * The associated suggestion object will serve as the context. + * Used to render a single suggestion. + * If set, this has to be a precompiled template. + * The associated suggestion object will serve as the context. * Defaults to the value of displayKey wrapped in a p tag i.e.

{{value}}

. */ suggestion?: (datum: any) => string; } - + /** * When initializing a typeahead, there are a number of options you can configure. */ interface Options { /** - * highlight: If true, when suggestions are rendered, + * highlight: If true, when suggestions are rendered, * pattern matches for the current query in text nodes will be wrapped in a strong element. - * Defaults to false. + * Defaults to false. */ highlight?: boolean; @@ -186,6 +186,7 @@ declare module Twitter.Typeahead { minLength?: number; } } + declare module Bloodhound { interface BloodhoundOptions @@ -203,14 +204,14 @@ declare module Bloodhound * @constructor * @param query tokenizer query */ - queryTokenizer?: any; + queryTokenizer?: any; /** - * The max number of suggestions to return from Bloodhound#get. + * The max number of suggestions to return from Bloodhound#get. * If not reached, the data source will attempt to backfill the suggestions from remote. Defaults to 5 */ limit?: number; /** - * If set, this is expected to be a function with the signature (remoteMatch, localMatch) that returns true if the datums are duplicates or false otherwise. + * If set, this is expected to be a function with the signature (remoteMatch, localMatch) that returns true if the datums are duplicates or false otherwise. * If not set, duplicate detection will not be performed. */ dupDetector?: (remoteMatch: T, localMatch: T) => boolean; @@ -233,8 +234,8 @@ declare module Bloodhound } /** - * Prefetched data is fetched and processed on initialization. - * If the browser supports localStorage, the processed data will be cached + * Prefetched data is fetched and processed on initialization. + * If the browser supports localStorage, the processed data will be cached * there to prevent additional network requests on subsequent page loads. */ interface PrefetchOptions @@ -244,13 +245,13 @@ declare module Bloodhound */ url: string; /** - * The time (in milliseconds) the prefetched data should be cached + * The time (in milliseconds) the prefetched data should be cached * in localStorage. Defaults to 86400000 (1 day). */ ttl?: number; /** * A function that transforms the response body into an array of datums. - * + * * @param parsedResponse Response body */ filter?: (parsedResponse: any) => T[]; @@ -270,37 +271,37 @@ declare module Bloodhound /** * Remote data is only used when the data provided by local and prefetch - * is insufficient. In order to prevent an obscene number of requests + * is insufficient. In order to prevent an obscene number of requests * being made to remote endpoint, typeahead.js rate-limits remote requests. */ interface RemoteOptions { /** - * A URL to make requests to when the data provided by local and + * A URL to make requests to when the data provided by local and * prefetch is insufficient. Required. */ url: string; /** - * The pattern in url that will be replaced with the user's query + * The pattern in url that will be replaced with the user's query * when a request is made. Defaults to %QUERY. */ wildcard?: string; /** - * Overrides the request URL. If set, no wildcard substitution will + * Overrides the request URL. If set, no wildcard substitution will * be performed on url. - * + * * @param url Replacement URL * @param uriEncodedQuery Encoded query * @returns A valid URL */ replace?: (url: string, uriEncodedQuery: string) => string; /** - * The function used for rate-limiting network requests. + * The function used for rate-limiting network requests. * Can be either 'debounce' or 'throttle'. Defaults to 'debounce'. */ rateLimitby?: string; /** - * The time interval in milliseconds that will be used by rateLimitFn. + * The time interval in milliseconds that will be used by rateLimitFn. * Defaults to 300. */ rateLimitWait?: number; @@ -357,18 +358,18 @@ declare class Bloodhound { */ public ttAdapter(): any; /** - * Kicks off the initialization of the suggestion engine. This includes processing the data provided through local and fetching/processing the data provided through prefetch. - * Until initialized, all other methods will behave as no-ops. + * Kicks off the initialization of the suggestion engine. This includes processing the data provided through local and fetching/processing the data provided through prefetch. + * Until initialized, all other methods will behave as no-ops. * Returns a jQuery promise which is resolved when engine has been initialized. - * - * After the initial call of initialize, how subsequent invocations of the method behave depends on the reinitialize argument. - * If reinitialize is falsy, the method will not execute the initialization logic and will just return the same jQuery promise returned by the initial invocation. + * + * After the initial call of initialize, how subsequent invocations of the method behave depends on the reinitialize argument. + * If reinitialize is falsy, the method will not execute the initialization logic and will just return the same jQuery promise returned by the initial invocation. * If reinitialize is truthy, the method will behave as if it were being called for the first time. - * + * * var promise1 = engine.initialize(); * var promise2 = engine.initialize(); * var promise3 = engine.initialize(true); - * + * * promise1 === promise2; * promise3 !== promise1 && promise3 !== promise2; */ @@ -388,7 +389,7 @@ declare class Bloodhound { */ public clearPrefetchCache(): void; /** - * If you're using remote, Bloodhound will cache the 10 most recent responses in an effort to provide a better user experience. + * If you're using remote, Bloodhound will cache the 10 most recent responses in an effort to provide a better user experience. * clearRemoteCache offers a way to programmatically clear said cache. */ public clearRemoteCache(): void; @@ -398,8 +399,8 @@ declare class Bloodhound { public noConflict(): any; /** - * Computes a set of suggestions for query. cb will be invoked with an array of datums that represent said set. - * cb will always be invoked once synchronously with suggestions that were available on the client. + * Computes a set of suggestions for query. cb will be invoked with an array of datums that represent said set. + * cb will always be invoked once synchronously with suggestions that were available on the client. * If those suggestions are insufficient (# of suggestions is less than limit) and remote was configured, cb may also be invoked asynchronously with the suggestions available on the client mixed with suggestions from the remote source. */ public get(query: string, cb: (datums: T[]) => void): void; diff --git a/valerie/valerie-tests.ts b/valerie/valerie-tests.ts index bf9ce7880..b33932e29 100644 --- a/valerie/valerie-tests.ts +++ b/valerie/valerie-tests.ts @@ -285,4 +285,51 @@ function RuleTests() { .rule(() => { return anyValue; }) .end(); -} \ No newline at end of file +} + +function ModelValidation() { + + var model = {}; + + var validatedModel = valerie.validatableModel(model) + .validateAll() + .end(); + +} + +function UtilsStaticTests() { + + var t1 = valerie.utils.asArray(1); + var t2 = valerie.utils.asArray([1,2]); + + var t3 = valerie.utils.asFunction(1); + var t4 = valerie.utils.asFunction(() => { return 1; }); + + var t5 = valerie.utils.isArray([1, 2]); + var t5 = valerie.utils.isArrayOrObject(1); + var t6 = valerie.utils.isFunction("x"); + var t7 = valerie.utils.isMissing(null); + var t8 = valerie.utils.isObject({}); + var t9 = valerie.utils.isString("test"); + + var opts: Valerie.ValidationOptions = {}; // all values are optional + var t10 = valerie.utils.mergeOptions(opts, opts); +} + +function ValidationResultStaticTests() { + + var t1 = valerie.ValidationResult.passedInstance; + + var t2 = valerie.ValidationResult.createFailedResult("message"); + +} + +function ValidationStateStaticTests() { + + var t1 = valerie.validationState.findIn({}); + var t2 = valerie.validationState.getFor({}); + var t3 = valerie.validationState.has({}); + + var state = {}; + var t4 = valerie.validationState.setFor({}, state); +} diff --git a/valerie/valerie.d.ts b/valerie/valerie.d.ts index 847e0a7a0..abe5aea28 100644 --- a/valerie/valerie.d.ts +++ b/valerie/valerie.d.ts @@ -7,7 +7,10 @@ /** * - * Extensions to KO functions to provide validation + * Extensions to KO functions to provide validation + * + * Version 1.2 - added more static methods to valerie object + * */ interface KnockoutObservable { // starts validation for observable @@ -23,7 +26,6 @@ interface KnockoutObservableArray { validate(validationOptions?: Valerie.ValidationOptions): Valerie.PropertyValidationState>; } - interface KnockoutObservableArrayFunctions { /** * Creates and sets a model validation state on a Knockout observable array.
@@ -198,8 +200,6 @@ interface KnockoutBindingHandlers { visibleWhenValid: KnockoutBindingHandler; } - - // // root valerie namespace - static methods // @@ -208,12 +208,10 @@ declare var valerie: Valerie.Static; // additional types for Valerie (all inside this namespace) declare module Valerie { - // // Static methods on valerie namespace // interface Static { - /** * Maps a source model to a destination model, including only applicable properties * @param {Object|Array} sourceModel the source model @@ -248,9 +246,78 @@ declare module Valerie { // (value should be observable or computed) validatableProperty(value: T, options?: ValidationOptions): PropertyValidationState; + // Validation result class + ValidationResult: ValidationResultStatic; + // additional namespaces for static methods: + converters: ConvertersStatic; + + /* + //TODO: additional namespaces/statics not yet used + dom: DomStatic; + formatting: FormattingStatic; + koBindingsHelper: KoBindingsHelperStatic; + koExtras: KoExtrasStatic; + rules: RulesStatic; + */ + + utils: UtilsStatic; + validationState: ValidationState; + + } + + interface ValidationResultStatic { + + passedInstance: ValidationResult; + + // static method to create validatio failed message + createFailedResult(message: string): ValidationResult; + } + + // Contains converters, always singletons. + interface ConvertersStatic { + + //TODO: other converters to be added + + passThrough: Valerie.IConverter; + } + + + interface UtilsStatic { + + // Creates a function that returns the given value as an array of one item, or simply returns the given value if it is already an array. + asArray(value: any): any[]; + + // Creates a function that returns the given value, or simply returns the given value if it is already a function + asFunction(value: T): () => T; + asFunction(fn: () => T): () => T; + + // Tests whether the given value is an array + isArray(value: any): boolean; + + // Tests whether the given value is an array or object. + isArrayOrObject(value: any): boolean; + + // Tests whether the given value is a function. + isFunction(value: any): boolean; + + // Tests whether the given value is "missing".undefined, null, an empty string or an empty array are considered to be "missing". + isMissing(value: any): boolean; + + // Tests whether the given value is an object. + isObject(value: any): boolean; + + // Tests whether the give value is a string. + isString(value: any): boolean; + + //Merges the given default options with the given options. + // - either parameter can be omitted and a clone of the other parameter will be returned + // - the merge is shallow + // - array properties are shallow cloned + mergeOptions(defaultOptions: ValidationOptions, options:any): ValidationOptions; + } // callback interface (see mapModel above) @@ -263,10 +330,175 @@ declare module Valerie { // ctor new: (model: any, options?: ModelValidationStateOptions) => ModelValidationState; - addValidationStates(validationStateOrStates: any): void; - model: any; options?: ModelValidationStateOptions + + // methods + + /** + * Adds validation states to this validation state.
+ * [fluent] + * @name valerie.ModelValidationState#addValidationStates + * @fluent + * @param {object|array.} validationStateOrStates the validation states to add + * @return {valerie.ModelValidationState} + */ + addValidationStates(validationStateOrStates: any): ModelValidationState; + + /** + * Sets the value or function used to determine if the model is applicable.
+ * [fluent] + * @name valerie.ModelValidationState#applicable + * @fluent + * @param {boolean|function} [valueOrFunction = true] the value or function to use + * @return {valerie.ModelValidationState} + */ + applicable(valueOrFunction: any): ModelValidationState; + + /** + * Clears the static summary of validation states that are in a failure state.
+ * [fluent] + * @name valerie.ModelValidationState#clearSummary + * @fluent + * @param {boolean} [clearSubModelSummaries = false] whether to clear the static summaries for sub-models + * @return {valerie.ModelValidationState} + */ + clearSummary(valueOrFunction: any): ModelValidationState; + + /*** + * Gets whether the model has failed validation. + * @return {boolean} + */ + failed(): boolean; + + /*** + * Gets the validation states that belong to the model that are in a failure state. + * @return {Valerie.IValidationState[]} + */ + failedStates(): Valerie.IValidationState[]; + + /*** + * Gets the name of the model. + * @return {string} + */ + getName(): string; + + isApplicable(): boolean; + message(): string; + passed(): boolean; + + /*** + * Gets or sets whether the computation that updates the validation result has been paused. + * @param {boolean} [value = false] true if the computation should be paused, false if the computation should not be paused + * @return {boolean} true if computation is paused, false otherwise + */ + paused(value: boolean): boolean; + + pending(): boolean; + + pendingStates(): IValidationState[]; + + refresh(): void; + + result(): ValidationResult; + + summary(): summaryItem[] + + /*** + * Gets or sets whether the model has been 'touched' by user action + */ + touched(value: boolean): boolean; + + + validationStates(): IValidationState[]; + + /** + * Includes any validation failures for this model in a validation summary.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + includeInSummary(): ModelValidationState; + + /** + * Sets the value or function used to determine the name of the model.
+ * [fluent] + * @fluent + * @param {string|function} valueOrFunction the value or function to use + * @return {valerie.ModelValidationState} + */ + name(valueOrFunction: any): ModelValidationState; + + /** + * Removes validation states.
+ * [fluent] + * @fluent + * @param {object|array.} validationStateOrStates the validation states to remove + * @return {valerie.ModelValidationState} + */ + removeValidationStates(validationStateOrStates: any): ModelValidationState; + + /** + * Stops validating the given sub-model by adding the validation state that belongs to it. + * @param {*} validatableSubModel the sub - model to start validating + * @return {valerie.ModelValidationState } + */ + startValidatingSubModel(validatableSubModel: any): ModelValidationState; + + /** + * Stops validating the given sub-model by removing the validation state that belongs to it. + * @param {*} validatableSubModel the sub-model to stop validating + * @return {valerie.ModelValidationState} + */ + stopValidatingSubModel(validatableSubModel: any): ModelValidationState; + + /** + * Updates the static summary of validation states that are in a failure state.
+ * [fluent] + * @fluent + * @param {boolean} [updateSubModelSummaries = false] whether to update the static summaries for sub-models + * @return {valerie.ModelValidationState} + */ + updateSummary(updateSubModelSummaries: boolean): ModelValidationState; + + /** + * Adds the validation states for all the descendant properties and sub-models that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateAll(): ModelValidationState; + + /** + * Adds the validation states for all the descendant properties that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateAllProperties(): ModelValidationState; + + /** + * Adds the validation states for all the child properties that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateChildProperties(): ModelValidationState; + + /** + * Adds the validation states for all the child properties and sub-models that belong to the model.
+ * [fluent] + * @fluent + * @return {valerie.ModelValidationState} + */ + validateChildPropertiesAndSubModels(): ModelValidationState; + + + /** + * Ends a chain of fluent method calls on this model validation state. + * @return {function} the model the validation state is for + */ + end(): any; } // Construction options for a model validation state. @@ -282,7 +514,6 @@ declare module Valerie { // PropertyValidationState // interface PropertyValidationState { - // properties: // the observable or computed the validation state is for @@ -310,12 +541,12 @@ declare module Valerie { during(earliest: () => Date, latest: Date, options?: ValidationOptions): PropertyValidationState; // dateFN + date during(earliest: Date, latest: () => Date, options?: ValidationOptions): PropertyValidationState; // date + dateFN during(earliest: () => Date, latest: () => Date, options?: ValidationOptions): PropertyValidationState; // dateFN + dateFN - earliest(earliest: Date, options?: ValidationOptions): PropertyValidationState; // date value + earliest(earliest: Date, options?: ValidationOptions): PropertyValidationState; // date value earliest(earliest: () => Date, options?: ValidationOptions): PropertyValidationState; // date function email(): PropertyValidationState; entryFormat(format: string): PropertyValidationState; excludeFromSummary(): PropertyValidationState; - expression(regularExpression: RegExp, options?: ValidationOptions): PropertyValidationState; // regex + expression(regularExpression: RegExp, options?: ValidationOptions): PropertyValidationState; // regex expression(regularExpressionString: string, options?: ValidationOptions): PropertyValidationState; // regex string float(options?: ValidationOptions): PropertyValidationState; integer(options?: ValidationOptions): PropertyValidationState; @@ -377,7 +608,6 @@ declare module Valerie { touched(): boolean; // get touched state touched(value: boolean): boolean; // set touched state result(): ValidationResult; - } interface ValidationResult { @@ -387,10 +617,6 @@ declare module Valerie { pending: boolean; //true if the activity hasn't yet completed message: string; //a message from the activity new: (state: any, message?: string) => ValidationResult; - - //TODO: not added static members/methods - createFailedResult(message: string): ValidationResult; - } interface IRule { @@ -411,7 +637,7 @@ declare module Valerie { } interface ValidatableModel { - name: (value:string) => PropertyValidationState; + name: (value: string) => PropertyValidationState; // return original observableArray end: () => T; @@ -438,7 +664,6 @@ declare module Valerie { // A helper for parsing and formatting numeric values. interface NumericHelper { - // Adds thousands separators to the given numeric string. addThousandsSeparator(numericString: string): string; @@ -468,13 +693,10 @@ declare module Valerie { // Unformats a numeric string; removes currency signs, thousands separators and normalises decimal separators. unformat(numericString: string): string; - } - interface ValidationState { - - // Finds and returns the validation states + // Finds and returns the validation states findIn(model: any, includeSubModels?: boolean, recurse?: boolean, @@ -486,18 +708,20 @@ declare module Valerie { // nforms if the given model, observable or computed has a validation state. has(modelOrObservableOrComputed: any): boolean; - // Sets the validation state for the given model, observable or computed. setFor(modelOrObservableOrComputed: any, state: IValidationState): void; + } + interface summaryItem { + name: string; + message: string; } } declare module Valerie.Rules { - /* Todo: add classes in valerie.rules namespace */ -} \ No newline at end of file +} diff --git a/winjs/winjs-1.0.d.ts b/winjs/winjs-1.0.d.ts index 0952b03fe..7e46ed53f 100644 --- a/winjs/winjs-1.0.d.ts +++ b/winjs/winjs-1.0.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -362,6 +362,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -432,7 +438,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -539,7 +545,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -599,7 +605,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -607,7 +613,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -661,7 +667,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -714,6 +720,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -727,6 +734,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -934,30 +942,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?: any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1085,6 +1091,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1101,7 +1113,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1157,10 +1169,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1179,7 +1205,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1191,34 +1217,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1240,7 +1272,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1248,7 +1280,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1257,7 +1289,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1266,7 +1298,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1275,7 +1307,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1284,7 +1316,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1294,7 +1382,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1302,21 +1390,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1332,7 +1420,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: () => string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1356,8 +1445,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?: (request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1518,7 +1608,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1623,7 +1713,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1639,7 +1729,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1656,7 +1746,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1664,7 +1754,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1672,7 +1762,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1680,7 +1770,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1703,7 +1793,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1741,7 +1831,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1749,7 +1839,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1757,7 +1847,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Performs a deselection animation in response to a swipe interaction. @@ -1773,7 +1863,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1789,7 +1879,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; //#endregion Functions @@ -2244,32 +2334,10 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2278,16 +2346,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + retain(): IItemPromise; //#endregion Methods @@ -4608,7 +4667,7 @@ declare module WinJS.UI { * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; /** * Shows the specified commands of the Menu. @@ -5511,6 +5570,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -5577,9 +5643,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -5679,6 +5745,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -5695,6 +5762,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -5716,7 +5784,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -5724,14 +5792,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -5739,7 +5807,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -5747,7 +5815,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -5765,11 +5833,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } //#endregion Objects @@ -5781,14 +5844,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -5798,7 +5861,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -6362,6 +6425,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -6416,7 +6485,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -6537,7 +6606,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -6545,7 +6614,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -6663,6 +6732,7 @@ declare module WinJS.Utilities { * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -6691,10 +6761,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { diff --git a/winjs/winjs-2.0.d.ts b/winjs/winjs-2.0.d.ts index 205b41889..508973a50 100644 --- a/winjs/winjs-2.0.d.ts +++ b/winjs/winjs-2.0.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -372,6 +372,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -442,7 +448,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -549,7 +555,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -609,7 +615,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -617,7 +623,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -671,7 +677,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -724,6 +730,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -737,6 +744,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -944,30 +952,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?: any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1128,6 +1134,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1144,7 +1156,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1200,10 +1212,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1222,7 +1248,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1234,34 +1260,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1283,7 +1315,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1291,7 +1323,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1300,7 +1332,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1309,7 +1341,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1318,7 +1350,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1327,7 +1359,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1337,7 +1425,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1345,21 +1433,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1375,7 +1463,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: () => string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1399,8 +1488,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?: (request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1561,7 +1651,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1666,7 +1756,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1682,7 +1772,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1699,7 +1789,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1707,7 +1797,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1715,7 +1805,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1723,7 +1813,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1746,7 +1836,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1754,7 +1844,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function hidePanel(element: any, offset: any): Promise; + function hidePanel(element: any, offset?: any): Promise; /** * Performs an animation that removes pop-up user interface (UI). @@ -1784,7 +1874,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1792,7 +1882,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1800,7 +1890,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Performs a deselection animation in response to a swipe interaction. @@ -1816,7 +1906,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1832,7 +1922,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; //#endregion Functions @@ -2329,32 +2419,9 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events - + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2363,16 +2430,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + retain(): IItemPromise; //#endregion Methods @@ -3254,6 +3312,11 @@ declare module WinJS.UI { * Gets or sets whether the ListView item is focused and is showing its focus visual. **/ showFocus?: boolean; + + /** + * Gets the type, if any. + **/ + type?: WinJS.UI.ObjectType; } /** @@ -4264,7 +4327,7 @@ declare module WinJS.UI { * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; //#endregion Methods @@ -4350,6 +4413,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -4670,7 +4741,7 @@ declare module WinJS.UI { /** * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. **/ - zoomableView: IZoomableView; + zoomableView: IZoomableView; //#endregion Properties @@ -4919,6 +4990,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -5511,7 +5590,7 @@ declare module WinJS.UI { * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; /** * Shows the specified commands of the Menu. @@ -6136,9 +6215,10 @@ declare module WinJS.UI { /** * Creates a new Repeater control. * @constructor + * @param elemnt The DOM element that will host the new control. The Repeater will create an element if this value is null. * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". **/ - constructor(options?: any); + constructor(element?: HTMLElement, options?: any); //#endregion Constructors @@ -6411,6 +6491,8 @@ declare module WinJS.UI { //#endregion Properties + static createResultSuggestionImage(url: string): any; + } /** @@ -7110,6 +7192,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -7176,9 +7265,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -7278,6 +7367,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -7294,6 +7384,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -7315,7 +7406,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -7323,14 +7414,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -7338,7 +7429,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -7346,7 +7437,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -7364,11 +7455,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } //#endregion Objects @@ -7380,14 +7466,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -7397,7 +7483,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -7961,6 +8047,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -8015,7 +8107,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -8142,7 +8234,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -8150,7 +8242,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -8202,7 +8294,7 @@ declare module WinJS.Utilities { * @param element The element to mark as disposable. * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + function markDisposable(element: HTMLElement, disposeImpl?: Function): void; /** * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. @@ -8275,6 +8367,7 @@ declare module WinJS.Utilities { * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -8303,10 +8396,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { @@ -8470,6 +8563,15 @@ declare module WinJS.Utilities.Scheduler { //#endregion Interfaces + //#region Properties + + /** + * Gets the current priority at which the caller is executing. + **/ + var currentPriority: Priority; + + //#endregion Properties + //#region Functions /** diff --git a/winjs/winjs-2.1.d.ts b/winjs/winjs-2.1.d.ts index 66afeb69e..5c8f53641 100644 --- a/winjs/winjs-2.1.d.ts +++ b/winjs/winjs-2.1.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -378,6 +378,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -448,7 +454,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -555,7 +561,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -615,7 +621,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -623,7 +629,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -677,7 +683,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -730,6 +736,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -743,6 +750,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -950,30 +958,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?: any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1143,6 +1149,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1159,7 +1171,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1215,10 +1227,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1237,7 +1263,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1249,34 +1275,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1298,7 +1330,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1306,7 +1338,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1315,7 +1347,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1324,7 +1356,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1333,7 +1365,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1342,7 +1374,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1352,7 +1440,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1360,21 +1448,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1390,7 +1478,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: () => string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1414,8 +1503,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?: (request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1576,7 +1666,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1722,7 +1812,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1738,7 +1828,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1755,7 +1845,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1763,7 +1853,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1771,7 +1861,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1779,7 +1869,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1802,7 +1892,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1810,7 +1900,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function hidePanel(element: any, offset: any): Promise; + function hidePanel(element: any, offset?: any): Promise; /** * Performs an animation that removes pop-up user interface (UI). @@ -1840,7 +1930,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1848,7 +1938,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1856,7 +1946,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Slides elements off through the bottom of the screen. @@ -1926,7 +2016,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1971,7 +2061,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; //#endregion Functions @@ -2469,32 +2559,10 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2503,18 +2571,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; - - //#endregion Methods + retain(): IItemPromise; //#region Properties @@ -3394,6 +3451,11 @@ declare module WinJS.UI { * Gets or sets whether the ListView item is focused and is showing its focus visual. **/ showFocus?: boolean; + + /** + * Gets the type, if any. + **/ + type?: WinJS.UI.ObjectType; } /** @@ -4076,6 +4138,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -4462,6 +4532,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -5056,7 +5134,7 @@ declare module WinJS.UI { /** * Gets or sets the header for this PivotItem. **/ - header: HTMLElement; + header: string; //#endregion Properties } @@ -5070,9 +5148,10 @@ declare module WinJS.UI { /** * Creates a new Repeater control. * @constructor + * @param elemnt The DOM element that will host the new control. The Repeater will create an element if this value is null. * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". **/ - constructor(options?: any); + constructor(element?: HTMLElement, options?: any); //#endregion Constructors @@ -5544,6 +5623,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -5610,9 +5696,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -5719,6 +5805,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -5735,6 +5822,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -5756,7 +5844,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -5764,14 +5852,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -5779,7 +5867,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -5787,7 +5875,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -5805,12 +5893,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } - //#endregion Objects //#region Functions @@ -5821,14 +5903,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -5838,7 +5920,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -6402,6 +6484,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -6456,7 +6544,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -6583,7 +6671,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -6591,7 +6679,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -6643,7 +6731,7 @@ declare module WinJS.Utilities { * @param element The element to mark as disposable. * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + function markDisposable(element: HTMLElement, disposeImpl?: Function): void; /** * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. @@ -6716,6 +6804,7 @@ declare module WinJS.Utilities { * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -6749,10 +6838,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { @@ -6916,6 +7005,15 @@ declare module WinJS.Utilities.Scheduler { //#endregion Interfaces + //#region Properties + + /** + * Gets the current priority at which the caller is executing. + **/ + var currentPriority: Priority; + + //#endregion Properties + //#region Functions /** diff --git a/winjs/winjs.d.ts b/winjs/winjs.d.ts index 811e4893f..195ecb66e 100644 --- a/winjs/winjs.d.ts +++ b/winjs/winjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for WinJS -// Project: http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx -// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure +// Project: http://try.buildwinjs.com/ +// Definitions by: TypeScript samples , Adam Hewitt , Craig Treasure , Jeff Fisher // Definitions: https://github.com/borisyankov/DefinitelyTyped /* ***************************************************************************** @@ -22,7 +22,7 @@ and limitations under the License. * Defines an Element object. **/ interface Element { - winControl: any; // TODO: This should be control? + winControl: any; } /** @@ -55,7 +55,7 @@ interface IOHelper { * Writes the specified text to the specified file. * @param fileName The name of the file. * @param text The content to be written to the file. - * @returns A promise that completes with a value that is the number of characters written. + * @returns A promise that is completed when the file has been written. **/ writeText(fileName: string, text: string): WinJS.Promise; } @@ -372,6 +372,12 @@ declare module WinJS.Binding { //#endregion Properties + /** + * Returns a key/data pair for the specified index. + * @param index The index of the value to retrieve. + * @returns An object that has two properties: key and data. + **/ + getItem(index: number): IGroupKeyDataPair; } /** @@ -442,7 +448,7 @@ declare module WinJS.Binding { * Returns a list with the elements sorted. This method sorts the elements of a list object in place. It does not create a new list object during execution. * @param sortFunction The function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. This function must always return the same results, given the same inputs. The results should not depend on values that are subject to change. You must call notifyMutated each time an item changes. Do not batch change notifications. **/ - sort(sortFunction: (left: T, right: T) => number): void; + sort(sortFunction?: (left: T, right: T) => number): void; /** * Removes elements from a list and, if necessary, inserts new elements in their place, returning the deleted elements. @@ -549,7 +555,7 @@ declare module WinJS.Binding { * @param groupSorter A function that accepts two arguments. The function is called with pairs of group keys found in the list. It must return one of the following numeric values: negative if the first argument is less than the second (sorted before), zero if the two arguments are equivalent, positive if the first argument is greater than the second (sorted after). * @returns A grouped projection over the list. **/ - createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter: (left: string, right: string) => number): GroupedSortedListProjection; + createGrouped(groupKey: (x: T) => string, groupData: (x: T) => any, groupSorter?: (left: string, right: string) => number): GroupedSortedListProjection; /** * Creates a live sorted projection over this list. As the list changes, the sorted projection reacts to those changes and may also change. @@ -609,7 +615,7 @@ declare module WinJS.Binding { * @param separator A string used to separate the elements of a list. If this parameter is omitted, the list elements are separated with a comma. * @returns The elements of a list separated by the specified separator string. **/ - join(separator: string): string; + join(separator?: string): string; /** * Gets the index of the last occurrence of the specified value in a list. @@ -617,7 +623,7 @@ declare module WinJS.Binding { * @param fromIndex The index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the list. * @returns The index of the last occurrence of a value in a list, or -1 if not found. **/ - lastIndexOf(searchElement: T, fromIndex: number): number; + lastIndexOf(searchElement: T, fromIndex?: number): number; /** * Calls the specified callback function on each element of a list, and returns an array that contains the results. @@ -671,7 +677,7 @@ declare module WinJS.Binding { * @param end The index that specifies the end of the section. * @returns Returns a section of list. **/ - slice(begin: number, end: number): T[]; + slice(begin: number, end?: number): T[]; /** * Checks whether the specified callback function returns true for any element of a list. @@ -724,6 +730,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ push(value: T): number; + push(...values: T[]): number; /** * Removes the first element from a list and returns it. @@ -737,6 +744,7 @@ declare module WinJS.Binding { * @returns The new length of the list. **/ unshift(value: T): number; + unshift(...values: T[]): number; //#endregion Methods } @@ -944,30 +952,28 @@ declare module WinJS.Binding { * @param element The DOM element to convert to a template. * @param options If this parameter is supplied, the template is loaded from the URI and the content of the element parameter is ignored. You can add the following options: href. **/ - constructor(element: HTMLElement, options?: string); + constructor(element: HTMLElement, options?:any); //#endregion Constructors //#region Methods - render: { - /** - * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. - **/ - (dataContext: any, container?: HTMLElement): Promise; + /** + * Binds values from the specified data context to elements that are descendants of the specified root element that have the declarative binding attributes specified (data-win-bind). + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A Promise that will be completed after binding has finished. The value is either container or the created DIV. promise that is completed after binding has finished. + **/ + render(dataContext: any, container?: HTMLElement): Promise; - /** - * Renders a template based on the specified URI (static method). - * @param href The URI from which to load the template. - * @param dataContext The object to use for default data binding. - * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. - * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. - **/ - value(href: string, dataContext: any, container?: HTMLElement): Promise; - }; + /** + * Renders a template based on the specified URI (static method). + * @param href The URI from which to load the template. + * @param dataContext The object to use for default data binding. + * @param container The element to which to add this rendered template. If this parameter is omitted, a new DIV is created. + * @returns A promise that is completed after binding has finished. The value is either the object in the container parameter or the created DIV. + **/ + static render(href: string, dataContext: any, container?: HTMLElement): Promise; //#endregion Methods @@ -1137,6 +1143,12 @@ declare module WinJS.Binding { data: T; } + interface IGroupKeyDataPair extends IKeyDataPair { + groupSize: number; + firstItemIndexHint: number; + firstItemKey: string; + } + //#endregion Interfaces } @@ -1153,7 +1165,7 @@ declare module WinJS.Class { * @param staticMembers The set of static fields, properties, and methods made available on the type. * @returns The newly-defined type. **/ - function define(constructor: Function, instanceMembers?: any, staticMembers?: any): any; + function define(constructor?: Function, instanceMembers?: any, staticMembers?: any): any; /** * Creates a sub-class based on the specified baseClass parameter, using prototype inheritance. @@ -1209,10 +1221,24 @@ declare module WinJS { } + interface IPromise { + cancel(): void; + done(onComplete?: (value: T) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): void; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + } + /** * Provides a mechanism to schedule work to be done on a value that has not yet been computed. It is an abstraction for managing interactions with asynchronous APIs. For more information about asynchronous programming, see Asynchronous programming. For more information about promises in JavaScript, see Asynchronous programming in JavaScript. For more information about using promises, see the WinJS Promise sample. **/ - class Promise { + class Promise implements IPromise { //#region Constructors /** @@ -1231,7 +1257,7 @@ declare module WinJS { * Occurs when there is an error in processing a promise. * @param eventInfo An object that contains information about the event. **/ - onerror(eventInfo: CustomEvent): void; + static onerror(eventInfo: CustomEvent): void; //#endregion Events @@ -1243,34 +1269,40 @@ declare module WinJS { * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ - addEventListener(type: string, listener: Function, capture?: boolean): void; + static addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Returns a promise that is fulfilled when one of the input promises has been fulfilled. * @param value An array that contains Promise objects or objects whose property values include Promise objects. * @returns A promise that on fulfillment yields the value of the input (complete or error). **/ - static any(value: Promise[]): Promise; + static any(value: IPromise[]): IPromise; + static any(value: any): IPromise; /** * Returns a promise. If the object is already a Promise it is returned; otherwise the object is wrapped in a Promise. You can use this function when you need to treat a non-Promise object like a Promise, for example when you are calling a function that expects a promise, but already have the value needed rather than needing to get it asynchronously. * @param value The value to be treated as a Promise. * @returns The promise. **/ - static as(value: U): Promise; + static as(value?: U): IPromise; /** * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). **/ cancel(): void; + /** + * Canceled promise value, can be returned from a promise completion handler to indicate cancelation of the promise chain. + */ + static cancel: IPromise; + /** * Raises an event of the specified type and properties. * @param type The type (name) of the event. * @param details The set of additional properties to be attached to the event object. * @returns true if preventDefault was called on the event; otherwise, false. **/ - dispatchEvent(type: string, details: any): boolean; + static dispatchEvent(type: string, details: any): boolean; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1292,7 +1324,7 @@ declare module WinJS { * @param values An object whose members contain values, some of which may be promises. * @returns A Promise whose value is an object with the same field names as those of the object in the values parameter, where each field value is the fulfilled value of a promise. **/ - static join(values: any): Promise; + static join(values: any): IPromise; /** * Removes an event listener from the control. @@ -1300,7 +1332,7 @@ declare module WinJS { * @param listener The listener to remove. * @param capture Specifies whether or not to initiate capture. **/ - removeEventListener(eventType: string, listener: Function, capture?: boolean): void; + static removeEventListener(eventType: string, listener: Function, capture?: boolean): void; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1309,7 +1341,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1318,7 +1350,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => Promise, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1327,7 +1359,7 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => Promise, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => IPromise, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; /** * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. @@ -1336,7 +1368,63 @@ declare module WinJS { * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. * @returns The promise whose value is the result of executing the onComplete function. **/ - then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): Promise; + then(onComplete?: (value: T) => U, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => U, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => IPromise, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => U, onProgress?: (progress: any) => void): IPromise; + + /** + * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. For more information about the differences between then and done, see the following topics: Quickstart: using promises in JavaScript How to handle errors when using promises in JavaScript Chaining promises in JavaScript. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + then(onComplete?: (value: T) => void, onError?: (error: any) => void, onProgress?: (progress: any) => void): IPromise; + + + /** + * A static helper that functions identically to then() off a promise instance. + * @param promise The promise to chain from. + * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. + * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. In different cases this object may be of different types, so it is necessary to test the object for the properties you expect. If the error is null, it is forwarded. The value returned from the function becomes the value of the promise returned by the then function. + * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. + * @returns The promise whose value is the result of executing the onComplete function. + **/ + static then(promise: IPromise, onComplete?: (value: any) => any, onError?: (error: any) => any, onProgress?: (progress: any) => void): IPromise; /** * Performs an operation on all the input promises and returns a promise that has the shape of the input and contains the result of the operation that has been performed on each input. @@ -1346,7 +1434,7 @@ declare module WinJS { * @param progress The function to be called if the promise reports progress. This function takes a single argument, which is the data about the progress of the promise. Promises are not required to support progress. * @returns A Promise that is the result of calling join on the values parameter. **/ - static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): Promise; + static thenEach(values: any, complete?: (value: any) => void, error?: (error: any) => void, progress?: (progress: any) => void): IPromise; /** * This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise). WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period. @@ -1354,21 +1442,21 @@ declare module WinJS { * @param promise Optional. A promise that will be canceled if it doesn't complete within the timeout period. * @returns If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned. **/ - static timeout(timeout: number, promise?: Promise): Promise; + static timeout(timeout?: number, promise?: IPromise): IPromise; /** * Wraps a non-promise value in a promise. This method is like wrapError, which allows you to produce a Promise in error conditions, in that it allows you to return a Promise in success conditions. * @param value Some non-promise value to be wrapped in a promise. * @returns A promise that is successfully fulfilled with the specified value. **/ - static wrap(value: U): Promise; + static wrap(value?: U): IPromise; /** * Wraps a non-promise error value in a promise. You can use this function if you need to pass an error to a function that requires a promise. * @param error A non-promise error value to be wrapped in a promise. * @returns A promise that is in an error state with the specified value. **/ - static wrapError(error: U): Promise; + static wrapError(error: U): IPromise; //#endregion Methods @@ -1384,7 +1472,8 @@ declare module WinJS { * @param tags The tag or tags to categorize the message (winjs, winjs controls, etc.). * @param type The type of message (error, warning, info, etc.). **/ - function log(message: string, tags: string, type: string): void; + function log(message: string, tags?: string, type?: string): void; + function log(message: ()=>string, tags?: string, type?: string): void; /** * This method has been deprecated. Strict processing is always on; you don't have to call this method to turn it on. @@ -1408,8 +1497,9 @@ declare module WinJS { user?: string; password?: string; headers?: any; - data: any; + data?: any; responseType?: string; + customRequestInitializer?:(request: XMLHttpRequest) => void; } //#endregion Interfaces @@ -1570,7 +1660,7 @@ declare module WinJS.Resources { * Processes data-win-res attributes on elements and replaces attributes and properties with resource strings. * @param rootElement The element to process. The element and its child elements will be processed. If an element isn't specified, the entire document is processed. **/ - function processAll(rootElement?: HTMLElement): void; + function processAll(rootElement?: HTMLElement): Promise; /** * Removes an event listener that the addEventListener method registered. @@ -1675,7 +1765,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function dragBetweenEnter(target: any, offset: any): Promise; + function dragBetweenEnter(target: any, offset?: any): Promise; /** * Performs an animation when a dragged object is moved away from items that it had previously involved in a dragBetweenEnter animation. The affected objects are animated back to their original positions. @@ -1691,7 +1781,7 @@ declare module WinJS.UI.Animation { * @param affected Element or elements whose position the dropped object affects. Typically, this is all other items in a reorderable list. This should be the same element or element collection passed as the affected parameter in the dragSourceStart animation. * @returns An object that completes when the animation is finished. **/ - function dragSourceEnd(dragSource: any, offset: any, affected?: any): Promise; + function dragSourceEnd(dragSource: any, offset?: any, affected?: any): Promise; /** * Performs an animation when the user begins to drag an object. @@ -1708,7 +1798,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function enterContent(incoming: any, offset: any, options?: any): Promise; + function enterContent(incoming: any, offset?: any, options?: any): Promise; /** * Performs an animation that shows a new page of content, either when transitioning between pages in a running app or when displaying the first content in a newly launched app. @@ -1716,7 +1806,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the element or elements begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function enterPage(element: any, offset: any): Promise; + function enterPage(element: any, offset?: any): Promise; /** * Performs an animation that hides one or more elements on a page. @@ -1724,7 +1814,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitContent(outgoing: any, offset: any): Promise; + function exitContent(outgoing: any, offset?: any): Promise; /** * Performs an animation that dismisses the current page when transitioning between pages in an app. @@ -1732,7 +1822,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function exitPage(outgoing: any, offset: any): Promise; + function exitPage(outgoing: any, offset?: any): Promise; /** * Performs an animation that fades an item or set of items into view. @@ -1755,7 +1845,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function hideEdgeUI(element: any, offset: any, options?: any): Promise; + function hideEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that hides a panel. @@ -1763,7 +1853,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements end the animation just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function hidePanel(element: any, offset: any): Promise; + function hidePanel(element: any, offset?: any): Promise; /** * Performs an animation that removes pop-up user interface (UI). @@ -1793,7 +1883,7 @@ declare module WinJS.UI.Animation { * @param options Optional. Set this value to { mechanism: "transition" } to play the animation using CSS transitions instead of the default CSS animations. In some cases this can result in improved performance. * @returns An object that completes when the animation is finished. **/ - function showEdgeUI(element: any, offset: any, options?: any): Promise; + function showEdgeUI(element: any, offset?: any, options?: any): Promise; /** * Performs an animation that slides a large panel user interface (UI) into view. @@ -1801,7 +1891,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPanel(element: any, offset: any): Promise; + function showPanel(element: any, offset?: any): Promise; /** * Performs an animation that displays a pop-up user interface (UI). @@ -1809,7 +1899,7 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where the animated objects begin relative to their final position at the end of the animation. Offsets should be the chosen so that the elements begin the animation from just off-screen. Set this parameter to null to use the recommended default offset. Note When the element parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function showPopup(element: any, offset: any): Promise; + function showPopup(element: any, offset?: any): Promise; /** * Performs a deselection animation in response to a swipe interaction. @@ -1825,7 +1915,7 @@ declare module WinJS.UI.Animation { * @param offset An initial offset where the animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function swipeReveal(target: any, offset: any): Promise; + function swipeReveal(target: any, offset?: any): Promise; /** * Performs a selection animation in response to a swipe interaction. @@ -1841,7 +1931,122 @@ declare module WinJS.UI.Animation { * @param offset Initial offsets where incoming animated objects begin relative to their final position at the end of the animation. Set this parameter to null to use the recommended default offset. Note When the incoming parameter specifies an array of elements, the offset parameter can specify an offset array with each item specified for its corresponding element array item. If the array of offsets is smaller than the array of elements, the last offset is applied to all remaining elements. * @returns An object that completes when the animation is finished. **/ - function updateBadge(incoming: any, offset: any): Promise; + function updateBadge(incoming: any, offset?: any): Promise; + + /** + * Execute a slide up animation. + * @param incoming Single element or collection of elements to animate sliding up. + * @returns A Promise that completes when the animation is finished. + **/ + function slideUp(incoming: any): Promise; + + /** + * Execute a slide down animation. + * @param incoming Single element or collection of elements to animate sliding down. + * @returns A Promise that completes when the animation is finished. + **/ + function slideDown(incoming: any): Promise; + + /** + * Execute a slide in from right to left animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding in. + * @param second Second element or collection of elements to animate sliding in, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding in, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideLeftIn(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a slide out from right to left animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding out. + * @param second Second element or collection of elements to animate sliding out, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding out, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideLeftOut(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a slide in from left to right animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding in. + * @param second Second element or collection of elements to animate sliding in, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding in, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideRightIn(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a slide out from left to right animation. + * @param page The page containing all elements to slide. + * @param first First element or collection of elements to animate sliding out. + * @param second Second element or collection of elements to animate sliding out, which will be offset slightly farther than the first. + * @param third Third element or collection of elements to animate sliding out, which will be offset slightly farther than the second. + * @returns A Promise that completes when the animation is finished. + **/ + function slideRightOut(page: any, first: any, second: any, third: any): Promise; + + /** + * Execute a continuum animation, scaling up the incoming page while scaling, rotating, and translating the incoming item. + * @param page Single element to be scaled up that is the page root and does not contain the incoming item. + * @param itemRoot Root of the item that will be translated as part of the continuum animation. + * @param itemContent Content of the item that will be scaled and rotated as part of the continuum animation. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumForwardIn(page: any, itemRoot: any, itemContent: any): Promise; + + /** + * Execute a continuum animation, scaling down the outgoing page while scaling, rotating, and translating the outgoing item. + * @param page Single element to be scaled down that is the page root and contains the outgoing item. + * @param item Single element to be scaled, rotated, and translated away from the outgoing page. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumForwardOut(page: any, item: any): Promise; + + /** + * Execute a continuum animation, scaling down the incoming page while scaling, rotating, and translating the incoming item. + * @param page Single element to be scaled down that is the page root and contains the incoming item. + * @param item Single element to be scaled, rotated, and translated into its final position on the page. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumBackwardIn(page: any, item: any): Promise; + + /** + * Execute a continuum animation, scaling down the outgoing page while. + * @param page Single element to be scaled down that is the page root. + * @returns A Promise that completes when the animation is finished. + **/ + function continuumBackwardOut(page: any): Promise; + + /** + * Execute a turnstile forward in animation. + * @param incoming Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileForwardIn(incoming: any): Promise; + + /** + * Execute a turnstile forward out animation. + * @param outgoing Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileForwardOut(outgoing: any): Promise; + + /** + * Execute a turnstile backward in animation. + * @param incoming Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileBackwardIn(incoming: any): Promise; + + /** + * Execute a turnstile backward out animation. + * @param outgoing Single element or collection of elements to animate. + * @returns A Promise that completes when the animation is finished. + **/ + function turnstileBackwardOut(outgoing: any): Promise; + //#endregion Functions @@ -2338,32 +2543,10 @@ declare module WinJS.UI { /** * Provides a mechanism for retrieving IItem objects asynchronously. **/ - interface IItemPromise { - //#region Events - - /** - * Occurs when there is an error in processing. - * @param eventInfo An object that contains information about the event. - **/ - onerror(eventInfo: CustomEvent): void; - - //#endregion Events + interface IItemPromise extends IPromise { //#region Methods - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - **/ - cancel(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. After the handlers have finished executing, this function throws any error that would have been returned from then as a promise in the error state. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The fulfilled value is passed as the single argument. If the value is null, the fulfilled value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while executing the function, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function is the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - **/ - done(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): void; - /** * Stops change notification tracking for the IItem that fulfills this IItemPromise. **/ @@ -2372,16 +2555,7 @@ declare module WinJS.UI { /** * Begins change notification tracking for the IItem that fulfills this IItemPromise. **/ - retain(): void; - - /** - * Allows you to specify the work to be done on the fulfillment of the promised value, the error handling to be performed if the promise fails to fulfill a value, and the handling of progress notifications along the way. - * @param onComplete The function to be called if the promise is fulfilled successfully with a value. The value is passed as the single argument. If the value is null, the value is returned. The value returned from the function becomes the fulfilled value of the promise returned by then. If an exception is thrown while this function is being executed, the promise returned by then moves into the error state. - * @param onError The function to be called if the promise is fulfilled with an error. The error is passed as the single argument. If it is null, the error is forwarded. The value returned from the function becomes the fulfilled value of the promise returned by then. - * @param onProgress The function to be called if the promise reports progress. Data about the progress is passed as the single argument. Promises are not required to support progress. - * @returns The promise whose value is the result of executing the complete or error function. - **/ - then(onComplete: (item: T) => void, onError?: (error: Error) => void, onProgress?: (progressData: any) => void): IItemPromise; + retain(): IItemPromise; //#endregion Methods @@ -3263,6 +3437,11 @@ declare module WinJS.UI { * Gets or sets whether the ListView item is focused and is showing its focus visual. **/ showFocus?: boolean; + + /** + * Gets the type, if any. + **/ + type?: WinJS.UI.ObjectType; } /** @@ -3550,6 +3729,11 @@ declare module WinJS.UI { //#region Properties + /** + * Gets/Sets how AppBar will display itself while hidden. Values are "none" and "minimal". + **/ + closedDisplayMode: string; + /** * Sets the AppBarCommand objects that appear in the app bar. **/ @@ -4273,7 +4457,7 @@ declare module WinJS.UI { * @param placement The placement of the Flyout to the anchor: the string literal "top", "bottom", "left", or "right". * @param alignment For "top" or "bottom" placement, the alignment of the Flyout to the anchor's edge: the string literal "center", "left", or "right". **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; //#endregion Methods @@ -4359,6 +4543,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -4679,7 +4871,7 @@ declare module WinJS.UI { /** * This API supports the SemanticZoom infrastructure and is not intended to be used directly from your code. **/ - zoomableView: IZoomableView; + zoomableView: IZoomableView; //#endregion Properties @@ -4928,6 +5120,14 @@ declare module WinJS.UI { **/ executeAnimations(): void; + /** + * Determines the next item to receive keyboard focus. + * @param currentItem An object that describes the current item. It has these properties: index, type. + * @param pressedKey The key that was pressed. + * @returns An object that describes the next item that should receive focus. It has these properties: index, type. + **/ + getAdjacent(currentItem: any, pressedKey: WinJS.Utilities.Key): any; + /** * This method is no longer supported. * @param itemIndex @@ -5428,6 +5628,157 @@ declare module WinJS.UI { } + /** + * A tab control that displays multiple items. +**/ + class Pivot { + //#region Constructors + + /** + * Creates a new Pivot. + * @constructor + * @param element The DOM element hosts the new Pivot. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Events + + /** + * Raised when a PivotItem control's animation ends. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationend(eventInfo: Event): void; + + /** + * Raised when a PivotItem control's animation starts. + * @param eventInfo An object that contains information about the event. + **/ + onitemanimationstart(eventInfo: Event): void; + + /** + * Raised when the user navigates to a different PivotItem. + * @param eventInfo An object that contains information about the event. + **/ + onselectionchanged(eventInfo: Event): void; + + //#endregion Events + + //#region Methods + + /** + * Registers an event handler for the specified event. + * @param eventName The name of the event to handle. + * @param eventHandler The event handler function to associate with the event. + * @param useCapture Set to true to register the event handler for the capturing phase; otherwise, set to false to register the event handler for the bubbling phase. + **/ + addEventListener(eventName: string, eventHandler: Function, useCapture?: boolean): void; + + /** + * Raises an event of the specified type and with additional properties. + * @param type The type (name) of the event. + * @param eventProperties The set of additional properties to be attached to the event object when the event is raised. + * @returns true if preventDefault was called on the event, otherwise false. + **/ + dispatchEvent(type: string, eventProperties: any): boolean; + + /** + * Releases resources held by this Pivot. Call this method when the Pivot is no longer needed. After calling this method, the Pivot becomes unusable. + **/ + dispose(): void; + + /** + * Removes an event handler that the addEventListener method registered. + * @param eventName The name of the event that the event handler is registered for. + * @param eventCallback The event handler function to remove. + * @param useCapture Set to true to remove the capturing phase event handler; set to false to remove the bubbling phase event handler. + **/ + removeEventListener(eventName: string, eventCallback: Function, useCapture?: boolean): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the Pivot control. + **/ + element: HTMLElement; + + /** + * Gets or sets the Binding.List that contains the PivotItem objects that belong to this Pivot. + **/ + items: Binding.List; + + /** + * Gets or sets a value that specifies whether the Pivot control is locked to the current item. + **/ + locked: boolean; + + /** + * Gets or sets the index of the PivotItem control in view. + **/ + selectedIndex: number; + + /** + * Gets or sets the PivotItem control in view within the Pivot control. + **/ + selectedItem: PivotItem; + + /** + * Gets or sets the title displayed above the PivotItem controls. + **/ + title: string; + + //#endregion Properties + } + + /** + * An item within a Pivot control. + **/ + class PivotItem { + //#region Constructors + + /** + * Creates a new PivotItem. + * @constructor + * @param element The DOM element hosts the new PivotItem. + * @param options An object that contains one or more property/value pairs to apply to the new control. Each property of the options object corresponds to one of the control's properties or events. Event names must begin with "on". For example, to provide a handler for the cancel event, add a property named "oncancel" to the options object and set its value to the event handler. + **/ + constructor(element?: HTMLElement, options?: any); + + //#endregion Constructors + + //#region Methods + + /** + * Releases resources held by this PivotItem. Call this method when the PivotItem is no longer needed. After calling this method, the PivotItem becomes unusable. + **/ + dispose(): void; + + //#endregion Methods + + //#region Properties + + /** + * Gets the DOM element that hosts the PivotItem control's content. + **/ + contentElement: HTMLElement; + + /** + * Gets the DOM element that hosts the PivotItem control. + **/ + element: HTMLElement; + + /** + * Gets or sets the header for this PivotItem. + **/ + header: string; + + //#endregion Properties + } + /** * Represents a menu flyout for displaying commands. **/ @@ -5520,7 +5871,7 @@ declare module WinJS.UI { * @param placement The placement of the Menu to the anchor: top, bottom, left, or right. * @param alignment For top or bottom placement, the alignment of the Menu to the anchor's edge: center, left, or right. **/ - show(anchor: HTMLElement, placement: string, alignment: string): void; + show(anchor: HTMLElement, placement?: string, alignment?: string): void; /** * Shows the specified commands of the Menu. @@ -6145,9 +6496,10 @@ declare module WinJS.UI { /** * Creates a new Repeater control. * @constructor + * @param elemnt The DOM element that will host the new control. The Repeater will create an element if this value is null. * @param options An object that contains one or more property/value pairs to apply to the new Repeater. Each property of the options object corresponds to one of the object's properties or events. Event names must begin with "on". **/ - constructor(options?: any); + constructor(element?:HTMLElement, options?: any); //#endregion Constructors @@ -6420,6 +6772,8 @@ declare module WinJS.UI { //#endregion Properties + static createResultSuggestionImage(url: string): any; + } /** @@ -7119,6 +7473,13 @@ declare module WinJS.UI { } + /** + * A special data source for VirtualizedDataSource.computeDataSourceGroups + **/ + interface IListGroupDataSource extends IListDataSource { + groups: IListDataSource; + } + /** * Serves as the base class for a custom IListDataSource. **/ @@ -7185,9 +7546,9 @@ declare module WinJS.UI { * @param groupKey A callback function that accepts a single argument: an item in the IListDataSource. The function is called for each item in the list and must return the group key for that item as a string. * @param groupData A callback function that accepts a single argument: an item in the IListDataSource. The function is called on one IListDataSource item for each group and must return an object that represents the header of that group. * @param options An object that can contain properties that specify additional options: groupCountEstimate, batchSize. - * @returns An IListDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. + * @returns An IListGroupDataSource that contains the items in the original data source and provides additional group information in the form of a "groups" property. The "groups" property returns another IListDataSource that enumerates the different groups in the list. **/ - function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListDataSource; + function computeDataSourceGroups(listDataSource: IListDataSource, groupKey: Function, groupData: Function, options?: any): IListGroupDataSource; /** * Used to disables all Animations Library and ListView animations. Calling this function does not guarantee that the animations will be disabled, as the determination is made based on several factors. @@ -7294,6 +7655,7 @@ declare module WinJS.UI.Fragments { * @param href The URI that contains the fragment to be cleared. If no URI is provided, the entire contents of the cache are cleared. **/ function clearCache(href: string): void; + function clearCache(href: HTMLElement): void; /** * Loads the contents of the specified URI into the specified element without copying it. @@ -7310,6 +7672,7 @@ declare module WinJS.UI.Fragments { * @returns A promise that is fulfilled when the fragment has been loaded. If a target element is not specified, the copied fragment is the completed value. The fragment is added to the cache. See also render, where the element is not added to the cache. **/ function renderCopy(href: string, target?: HTMLElement): Promise; + function renderCopy(href: HTMLElement, target?: HTMLElement): Promise; //#endregion Functions @@ -7331,7 +7694,7 @@ declare module WinJS.UI.Pages { * @param err The error that occurred. * @returns Nothing if the error was handled, or an error promise if the error was not handled. **/ - error? (err: any): Promise; + error? (err: any): any; /** * Initializes the control before the content of the control is set. Use the processed method for any initialization that should be done after the content of the control has been set. @@ -7339,14 +7702,14 @@ declare module WinJS.UI.Pages { * @param options The options passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - init? (element: HTMLElement, options: any): Promise; + init? (element: HTMLElement, options: any): any; /** * Creates DOM objects from the content in the specified URI. This method is called after the PageControl is defined and before the init method is called. * @param uri The URI from which to create DOM objects. * @returns A promise whose fulfilled value is the set of unparented DOM objects. **/ - load? (uri: string): Promise; + load? (uri: string): any; /** * Initializes the control after the content of the control is set. @@ -7354,7 +7717,7 @@ declare module WinJS.UI.Pages { * @param options The options that are to be passed to the constructor of the page. * @returns A promise that is fulfilled when initialization is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - processed? (element: HTMLElement, options: any): Promise; + processed? (element: HTMLElement, options: any): any; /** * Called after all initialization and rendering is complete. At this time, the element is ready for use. @@ -7362,7 +7725,7 @@ declare module WinJS.UI.Pages { * @param options An object that contains one or more property/value pairs to apply to the PageControl. How these property/value pairs are used (or not used) depends on the implementation of that particular PageControl. * @returns A promise that is fulfilled when the element is ready for use, if asynchronous processing is necessary. If not, returns nothing. **/ - ready? (element: HTMLElement, options: any): Promise; + ready? (element: HTMLElement, options: any): any; /** * Takes the elements returned by the load method and attaches them to the specified element. @@ -7380,12 +7743,6 @@ declare module WinJS.UI.Pages { //#region Objects - /** - * A modular unit of HTML, CSS, and JavaScript that can be navigated to or used as a custom WinJS control. - **/ - class PageControl { - } - //#endregion Objects //#region Functions @@ -7396,14 +7753,14 @@ declare module WinJS.UI.Pages { * @param members An object that defines the members that the control will have. * @returns A constructor function that creates the PageControl. **/ - function define(uri: string, members: IPageControlMembers): PageControl; + function define(uri: string, members: IPageControlMembers): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Gets an already-defined page control for the specified URI, or creates a new one. * @param uri The URI for the content that defines the page. * @returns A constructor function that creates the page. **/ - function get(uri: string): Function; + function get(uri: string): (element?: HTMLElement, options?: any, complete?: (page: any) => void, parentedPromise?: Promise) => void; /** * Creates a PageControl from the specified URI and inserts it inside the specified element. @@ -7413,7 +7770,7 @@ declare module WinJS.UI.Pages { * @param parentedPromise A Promise that is fulfilled when the new PageControl is done rendering and its contents becomes the child of element. * @returns A promise that is fulfilled when rendering is complete, if asynchronous processing is necessary. If not, returns nothing. **/ - function render(uri: string, element: HTMLElement, options?: any, parentedPromise?: Promise): Promise; + function render(uri: string, element?: HTMLElement, options?: any, parentedPromise?: Promise): Promise; //#endregion Functions @@ -7977,6 +8334,12 @@ declare module WinJS.Utilities { **/ include(items: T[]): void; + /** + * Adds a set of items to this QueryCollection. + * @param items The items to add to the QueryCollection. This may be an array-like object, a document fragment, or a single item. + **/ + include(items: HTMLCollection): void; + /** * Registers the listener for the specified event on all the elements in the collection. * @param eventType The name of the event. @@ -8031,7 +8394,7 @@ declare module WinJS.Utilities { * @param renderDonePromiseCallback If supplied, this function is called each time the template gets rendered, and is passed a promise that is fulfilled when the template rendering is complete. * @returns The QueryCollection. **/ - template(templateElement: HTMLElement, data: any, renderDonePromiseCallback: Function): QueryCollection; + template(templateElement: HTMLElement, data: any, renderDonePromiseCallback?: Function): QueryCollection; /** * Toggles (adds or removes) the specified class on all the elements in the collection. If the class is present, it is removed; if it is absent, it is added. @@ -8158,7 +8521,7 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative left coordinate. **/ - function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number; + function getRelativeLeft(element?: HTMLElement, parent?: HTMLElement): number; /** * Gets the top coordinate of the element relative to the specified parent. @@ -8166,7 +8529,21 @@ declare module WinJS.Utilities { * @param parent The parent element. * @returns The relative top coordinate. **/ - function getRelativeTop(element: HTMLElement, parent: HTMLElement): number; + function getRelativeTop(element?: HTMLElement, parent?: HTMLElement): number; + + /** + * Gets the scrollLeft and scrollTop of the specified element, adjusting the scrollLeft to change from browser specific coordinates to logical coordinates when in RTL. + * @param element The element. + * @returns An object with two properties: scrollLeft and scrollTop + **/ + function getScrollPosition(element: HTMLElement): { scrollLeft: number; scrollTop: number}; + + /** + * Gets the tab index of the specified element. + * @param element The element + * @returns The tabIndex of the element. Returns -1 if the element cannot be tabbed to. + **/ + function getTabIndex(element: HTMLElement): number; /** * Gets the height of the element, including its margins. @@ -8218,7 +8595,7 @@ declare module WinJS.Utilities { * @param element The element to mark as disposable. * @param disposeImpl The function containing the element-specific dispose logic, called by the dispose function that markDisposable attaches. **/ - function markDisposable(element: HTMLElement, disposeImpl: Function): void; + function markDisposable(element: HTMLElement, disposeImpl?: Function): void; /** * Marks a function as being compatible with declarative processing. Declarative processing is performed by WinJS.UI.processAll or WinJS.Binding.processAll. @@ -8286,11 +8663,19 @@ declare module WinJS.Utilities { **/ function setOuterHTMLUnsafe(element: HTMLElement, text: string): void; + /** + * Sets the scrollLeft and scrollTop of the specified element, changing the scrollLeft from logical coordinates to browser-specific coordinates when in RTL. + * @param element The element. + * @param position An object describing the position to set. + **/ + function setScrollPosition(element: HTMLElement, position: { scrollLeft: number; scrollTop: number}): void; + /** * Configures a logger that writes messages containing the specified tags to the JavaScript console. * @param options The tags for messages to log. Multiple tags should be separated by spaces. May contain type, tags, excludeTags and action properties. **/ function startLog(options?: ILogOptions): void; + function startLog(tags?: string): void; /** * Removes the WinJS logger that had previously been set up. @@ -8324,10 +8709,10 @@ declare module WinJS.Utilities { //#region Interfaces interface ILogOptions { - type: string; + type?: string; action?: (message: string, tags: string, type: string) => void; - excludeTags: string; - tags: string; + excludeTags?: string; + tags?: string; } interface IPosition { @@ -8491,6 +8876,15 @@ declare module WinJS.Utilities.Scheduler { //#endregion Interfaces + //#region Properties + + /** + * Gets the current priority at which the caller is executing. + **/ + var currentPriority: Priority; + + //#endregion Properties + //#region Functions /** diff --git a/winston/winston-tests.ts b/winston/winston-tests.ts index 499b427a6..0fa3cb442 100644 --- a/winston/winston-tests.ts +++ b/winston/winston-tests.ts @@ -4,14 +4,73 @@ import winston = require('winston'); var str: string; var bool: boolean; +var num: number; var metadata: any; +var obj: any = {}; + +var queryOptions: winston.QueryOptions; +var transportOptions: winston.TransportOptions; +var loggerOptions: winston.LoggerOptions = { + transports: [new (winston.Transport)()], + rewriters: [new (winston.Transport)()], + exceptionHandlers: [new (winston.Transport)()], + handleExceptions: false +}; + var options: any; var value: any; -var transport: winston.Transport; +var transport: winston.TransportInstance; +var logger: winston.LoggerInstance; +var profiler: winston.ProfileHandler; + +var writeableStream: NodeJS.WritableStream; +var readableStream: NodeJS.ReadableStream; + + +var transportStatic: winston.TransportStatic = winston.Transport; + + +var transportInstance: winston.TransportInstance = new (winston.Transport)(transportOptions); +transportInstance = new (winston.Transport)(); + +var containerInstance: winston.ContainerInstance = new (winston.Container)(loggerOptions); +winston.loggers.options.transports = [ + new (winston.Transport)() +]; +winston.loggers.add('category1', { + console: { + level: 'silly', + colorize: 'true', + label: 'category one' + }, + file: { + filename: '/path/to/some/file' + }, + transports: [ + new (winston.Transport)() + ] +}); +logger = winston.loggers.get('category1'); + +bool = containerInstance.has(str); +logger = containerInstance.get(str, loggerOptions); +containerInstance.close(str); -transport = winston.transports.File; transport = winston.transports.Console; +transport = winston.transports.DailyRotateFile; +transport = winston.transports.File; +transport = winston.transports.Http; transport = winston.transports.Loggly; +transport = winston.transports.Memory +transport = winston.transports.Webhook; + +value = transport.formatQuery({}); +queryOptions = transport.normalizeQuery(queryOptions); +value = transport.formatResults([], {}); +transport.logException(str, metadata, () => { }); + +winston.exitOnError = bool; + winston.log(str, str); winston.log(str, str, metadata); @@ -24,17 +83,139 @@ winston.warn(str, metadata); winston.error(str); winston.error(str, metadata); -winston.add(transport, options); -winston.remove(transport); +winston.query(queryOptions, (err: Error, results: any): void => { -winston.profile(str); - -winston.query(options, (err: any, results: any) => { +}); +winston.query((err: Error, results: any): void => { }); -value = winston.stream(options); +logger = winston.add(transport, transportOptions); +logger = winston.remove(transport); + +winston.clear(); +logger = winston.profile(str, str, metadata, (err: Error, level: string, msg: string, meta: any):void => { + +}); +logger = winston.profile(str); +profiler = winston.startTimer(); +winston.setLevels({}); +logger = winston.cli(); winston.handleExceptions(transport); -winston.exitOnError = bool; +winston.unhandleExceptions(transport); +readableStream = winston.stream(options); + +readableStream.on('log', function (log:any):void { + console.log(log); +}); + + + +logger = logger.extend(obj); +logger.log(str, str); +logger.log(str, str, metadata); +logger.debug(str); +logger.debug(str, metadata); +logger.info(str); +logger.info(str, metadata); +logger.warn(str); +logger.warn(str, metadata); +logger.error(str); +logger.error(str, metadata); + +logger.query(queryOptions, (err: Error, results: any): void => { + +}); +logger.query((err: Error, results: any): void => { + +}); + +readableStream = winston.stream(options); +logger.close(); +logger.handleExceptions(transport); +logger.unhandleExceptions(transport); +logger = logger.add(transport, transportOptions, bool); +logger = logger.add(transport); +logger.addRewriter(transport)[0]; +logger.clear(); +logger = logger.remove(transport); +profiler = logger.startTimer(); +logger = logger.profile(str, str, metadata, (err: Error, level: string, msg: string, meta: any):void => { + +}); +value = logger.setLevels(value); +logger = logger.cli(); + + +logger = profiler.done(str); +logger = profiler.logger; +profiler.start = new Date(); + + +/** + * New Logger instances with transports tests: + */ + +var logger: winston.LoggerInstance = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ + level: str, + silent: bool, + colorize: bool, + timestamp: bool, + }), + new (winston.transports.DailyRotateFile)({ + level: str, + silent: bool, + colorize: bool, + maxsize: num, + maxFiles: num, + prettyPrint: bool, + timestamp: bool, + filename: str, + dirname: str, + datePattern: str + }), + new (winston.transports.File)({ + level: str, + silent: bool, + timestamp: bool, + filename: str, + maxsize: num, + maxFiles: num, + stream: writeableStream, + }), + new (winston.transports.Http)({ + level: str, + host: str, + port: num, + path: str, + auth: { username: str, password: str }, + ssl: {}, + }), + new (winston.transports.Loggly)({ + level: str, + subdomain: str, + auth: {}, + inputName: str, + json: bool, + }), + new (winston.transports.Memory)({ + level: str, + timestamp: bool, + label: str, + }), + new (winston.transports.Webhook)({ + level: str, + name: str, + host: str, + port: num, + method: str, + path: str, + auth: { username: str, password: str }, + ssl: {}, + }), + ] +}); \ No newline at end of file diff --git a/winston/winston.d.ts b/winston/winston.d.ts index 8ebd618ff..4cf5370ca 100644 --- a/winston/winston.d.ts +++ b/winston/winston.d.ts @@ -1,39 +1,163 @@ // Type definitions for winston // Project: https://github.com/flatiron/winston -// Definitions by: bonnici +// Definitions by: bonnici , Peter Harris // Definitions: https://github.com/borisyankov/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/winston.d.ts +/// + declare module "winston" { - export function log(level: string, message: string, metadata?: any): void; - export function debug(message: string, metadata?: any): void; - export function info(message: string, metadata?: any): void; - export function warn(message: string, metadata?: any): void; - export function error(message: string, metadata?: any): void; - export function add(transport: Transport, options: any): void; - export function remove(transport: Transport): void; + export var transports: Transports; + export var Transport: TransportStatic; + export var Logger: LoggerStatic; + export var Container: ContainerStatic; + export var loggers: ContainerInstance; + export var defaultLogger: LoggerInstance; - export function profile(name: string): void; + export var exitOnError: boolean; - export function query(options: any, done: (err: any, results: any) => void): void; - export function stream(options: any): any; + export function log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function log(level: string, msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; - export function handleExceptions(transport: Transport): void; + export function debug(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function debug(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; - export class Logger { + export function info(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function info(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; - } + export function warn(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function warn(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; - export interface Transport { - } - export interface Transports { - File: Transport; - Console: Transport; - Loggly: Transport; - } - export var transports: Transports; - export var exitOnError: boolean; + export function error(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function error(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + export function query(options: QueryOptions, callback?: (err: Error, results: any) => void): any; + export function query(callback: (err: Error, results: any) => void): any; + export function stream(options?: any): NodeJS.ReadableStream; + export function handleExceptions(...transports: TransportInstance[]): void; + export function unhandleExceptions(...transports: TransportInstance[]): void; + export function add(transport: TransportInstance, options?: TransportOptions, created?: boolean): LoggerInstance; + export function clear(): void; + export function remove(transport: TransportInstance): LoggerInstance; + export function startTimer(): ProfileHandler; + export function profile(id: string, msg?: string, meta?: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + export function setLevels(target: any): any; + export function cli(): LoggerInstance; + + + export interface LoggerStatic { + new (options?: LoggerOptions); + } + + export interface LoggerInstance extends NodeJS.EventEmitter { + extend(target: any): LoggerInstance; + + log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + log(level: string, msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + debug(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + debug(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + info(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + info(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + warn(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + warn(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + error(msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + error(msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + query(options: QueryOptions, callback?: (err: Error, results: any) => void): any; + query(callback: (err: Error, results: any) => void): any; + stream(options?: any): NodeJS.ReadableStream; + close(): void; + handleExceptions(...transports: TransportInstance[]): void; + unhandleExceptions(...transports: TransportInstance[]): void; + add(transport: TransportInstance, options?: TransportOptions, created?: boolean): LoggerInstance; + addRewriter(rewriter: TransportInstance): TransportInstance[]; + clear(): void; + remove(transport: TransportInstance): LoggerInstance; + startTimer(): ProfileHandler; + profile(id: string, msg?: string, meta?: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; + + setLevels(target: any): any; + cli(): LoggerInstance; + } + + export interface LoggerOptions { + transports?: TransportInstance[]; + rewriters?: TransportInstance[]; + exceptionHandlers?: TransportInstance[]; + handleExceptions?: boolean; + + /** + * @type {(boolean|(err: Error) => void)} + */ + exitOnError?: any; + } + + export interface TransportStatic { + new (options?: TransportOptions): TransportInstance; + } + + export interface TransportInstance extends TransportStatic, NodeJS.EventEmitter { + formatQuery(query: any): any; + normalizeQuery(options: QueryOptions): QueryOptions; + formatResults(results: any, options: any): any; + logException(msg: string, meta: any, callback: () => void): void; + } + + export interface ContainerStatic { + new (options: LoggerOptions): ContainerInstance; + } + + export interface ContainerInstance extends ContainerStatic { + get(id: string, options?: LoggerOptions): LoggerInstance; + add(id: string, options: LoggerOptions): LoggerInstance; + has(id: string): boolean; + close(id: string): void; + options: LoggerOptions; + loggers: any; + default: LoggerOptions; + } + + export interface Transports { + File: TransportInstance; + Console: TransportInstance; + Loggly: TransportInstance; + DailyRotateFile: TransportInstance; + Http: TransportInstance; + Memory: TransportInstance; + Webhook: TransportInstance; + } + + export interface TransportOptions { + level?: string; + silent?: boolean; + raw?: boolean; + name?: string; + handleExceptions?: boolean; + } + + export interface QueryOptions { + rows?: number; + limit?: number; + start?: number; + from?: Date; + until?: Date; + /** + * 'asc' or 'desc' + */ + order?: string; + fields: any; + } + + export interface ProfileHandler { + logger: LoggerInstance; + start: Date; + done: (msg: string) => LoggerInstance; + } } diff --git a/zepto/zepto.d.ts b/zepto/zepto.d.ts index 04f11289e..d85072a66 100644 --- a/zepto/zepto.d.ts +++ b/zepto/zepto.d.ts @@ -493,6 +493,11 @@ interface ZeptoCollection { **/ appendTo(target: HTMLElement[]): ZeptoCollection; + /** + * @see ZeptoCollection.appendTo + **/ + appendTo(target: ZeptoCollection): ZeptoCollection; + /** * Read or set DOM attributes. When no value is given, reads specified attribute from the first element in the collection. When value is given, sets the attribute to that value on each element in the collection. When value is null, the attribute is removed (like with removeAttr). Multiple attributes can be set by passing an object with name-value pairs. * To read DOM properties such as checked or selected, use prop.