diff --git a/.travis.yml b/.travis.yml index d138403cc..acfc5176f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 0.10 + - "0.10" notifications: email: false diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 0fa132294..10ebf956d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,11 +8,13 @@ All definitions files include a header with the author and editors, so at some p * [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) * [Add To Home Screen](http://cubiq.org/add-to-home-screen) (by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw)) * [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) -* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga) +* [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga)) +* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga)) * [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/)) * [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)) @@ -28,6 +30,8 @@ All definitions files include a header with the author and editors, so at some p * [aws-sdk-js](https://github.com/aws/aws-sdk-js) (by [midknight41](https://github.com/midknight41)) * [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm)) +* [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet)) +* [BigInt](https://github.com/Evgenus/BigInt) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader)) * [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds)) @@ -38,9 +42,11 @@ All definitions files include a header with the author and editors, so at some p * [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [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)) * [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)) * [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber) and [otiai10](https://github.com/otiai10)) * [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay)) * [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik)) @@ -79,6 +85,7 @@ All definitions files include a header with the author and editors, so at some p * [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/)) +* [fingerprintjs](https://github.com/Valve/fingerprintjs) (by [Shunsuke Ohtani](https://github.com/zaneli)) * [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov)) * [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone)) * [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame)) @@ -110,6 +117,7 @@ All definitions files include a header with the author and editors, so at some p * [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy)) * [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov)) * [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [HashMap](https://github.com/flesler/hashmap) (by [Rafał Wrzeszcz](https://wrzasq.pl)) * [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home)) * [HelloJS](http://adodson.com/hello.js) (by [Pavel Zika](https://github.com/PavelPZ)) @@ -118,17 +126,21 @@ All definitions files include a header with the author and editors, so at some p * [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee)) * [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)) * [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)) * [interact.js](http://github.com/taye/interact.js) (by [Douglas Eichelberger](https://github.com/dduugg)) +* [Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) (by [Douglas Eichelberger](https://github.com/dduugg)) * [Ionic-Cordova](https://github.com/driftyco/) (by [Hendrik Maus](https://github.com/hendrikmaus)) * [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) * [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek)) * [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) * [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Jasmine-data_driven_tests](https://github.com/gburghardt/jasmine-data_driven_tests) (by [Anthony MacKinnon](https://github.com/AnthonyMacKinnon)) * [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac)) * [jDataView](https://github.com/jDataView/jDataView) (by [Ingvar Stepanyan](https://github.com/RReverser)) * [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel)) @@ -164,6 +176,7 @@ All definitions files include a header with the author and editors, so at some p * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.pjax](https://github.com/defunkt/jquery-pjax) (by [Junle Li](https://github.com/lijunle)) +* [jQuery.pjax.falsandtru](https://github.com/falsandtru/jquery.pjax.js/) (by [NewNotMoon](http://new.not-moon.net/)) * [jQuery.pnotify](http://sciactive.github.io/pnotify/) (by [David Sichau](https://github.com/DavidSichau/)) * [jQuery.postMessage](http://benalman.com/projects/jquery-postmessage-plugin/) (by [Junle Li](https://github.com/lijunle)) * [jQuery.prettyphoto](https://github.com/scaron/prettyphoto) (by [Paul Gaske](https://github.com/pgaske)) @@ -185,6 +198,7 @@ All definitions files include a header with the author and editors, so at some p * [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds)) * [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613)) * [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/)) +* [jsbn](http://www-cs-students.stanford.edu/%7Etjw/jsbn/) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) * [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/)) @@ -236,15 +250,19 @@ All definitions files include a header with the author and editors, so at some p * [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) * [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee)) * [mongoose](http://mongoosejs.com/) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) +* [morgan](https://github.com/expressjs/morgan/) (by [James Roland Cabresos](https://github.com/staticfunction/)) * [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz)) * [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [mysql](https://github.com/felixge/node-mysql) (by [William Johnston](https://github.com/wjohnsto)) * [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo)) +* [needle](https://github.com/tomas/needle) (by [San Chen](https://github.com/bigsan)) * [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook)) * [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-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)) @@ -253,10 +271,12 @@ All definitions files include a header with the author and editors, so at some p * [notify.js](https://github.com/alexgibson/notify.js) (by [soundTricker](https://github.com/soundTricker)) * [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [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/)) * [ocLazyLoad](https://github.com/ocombe/ocLazyLoad) (by [Roland Zwaga](https://github.com/rolandzwaga/)) * [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [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-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)) @@ -270,10 +290,14 @@ All definitions files include a header with the author and editors, so at some p * [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/)) * [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [ProgressJs](http://usablica.github.io/progress.js/) (by [Shunsuke Ohtani](https://github.com/zaneli)) +* [promise-pool](https://github.com/vilic/promise-pool) (by [VILIC VANE](https://github.com/vilic)) * [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar) * [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [q-retry](https://github.com/vilic/q-retry) (by [VILIC VANE](https://github.com/vilic)) * [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) * [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo)) +* [Recaptcha.js](https://www.google.com/recaptcha) (by [Brent Jenkins](https://github.com/brentj73)) * [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski)) * [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame)) * [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle)) @@ -284,16 +308,18 @@ All definitions files include a header with the author and editors, so at some p * [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) * [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov)) * [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [rtree.js] (https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) +* [rtree.js](https://github.com/leaflet-extras/RTree) (by [Omede Firouz](https://github.com/oefirouz)) * [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov)) * [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov)) * [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)) * [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)) * [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) * [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame)) * [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) +* [sjcl](http://crypto.stanford.edu/sjcl/) (by [Eugene Chernyshov](https://github.com/Evgenus)) * [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) * [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com)) * [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) @@ -301,6 +327,7 @@ All definitions files include a header with the author and editors, so at some p * [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) * [sockjs-node](https://github.com/sockjs/sockjs-node) (by [Phil McCloghry-Laing](https://github.com/pmccloghrylaing)) * [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [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)) * [status-bar](https://github.com/atom/status-bar) (by [vvakame](https://github.com/vvakame)) @@ -314,6 +341,7 @@ All definitions files include a header with the author and editors, so at some p * [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone)) * [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com)) * [text-buffer](https://github.com/atom/text-buffer) (by [vvakame](https://github.com/vvakame)) +* [text-encoding](https://github.com/inexorabletash/text-encoding) (by [MIZUNE Pine](https://github.com/pine613)) * [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/)) * [TimelineJS](https://github.com/NUKnightLab/TimelineJS) (by [Roland Zwaga](https://github.com/rolandzwaga)) * [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) (by [Rogier Schouten](https://github.com/rogierschouten)) diff --git a/angular-agility/angular-agility.d.ts b/angular-agility/angular-agility.d.ts index c11aff0b0..872971aed 100644 --- a/angular-agility/angular-agility.d.ts +++ b/angular-agility/angular-agility.d.ts @@ -41,7 +41,7 @@ declare module aa { [settingName: string]: any; } - export interface IFormExtensionsProvider extends ng.auto.IProvider { + export interface IFormExtensionsProvider extends ng.IServiceProvider { defaultLabelStrategy:string; defaultFieldGroupStrategy:string; defaultValMsgPlacementStrategy:string; @@ -88,7 +88,7 @@ declare module aa { message:string; } - export interface INotifyConfigProvider extends ng.auto.IProvider { + export interface INotifyConfigProvider extends ng.IServiceProvider { notifyConfigs:any; defaultTargetContainerName:string; defaultNotifyConfig:string; diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts new file mode 100644 index 000000000..21e9b2ce9 --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts @@ -0,0 +1,35 @@ +/// + +var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = []; +imageList.push({ + url: 'url1', + width: 100, + height: 100 +}); +imageList.push({ + url: 'url2', + width: 100, + height: 100, + thumbUrl: 'thumbUrl', + caption: 'caption' +}); + +var lightBox:angular.bootstrap.lightbox.ILightbox = {}; +lightBox.openModal(imageList, 0); + +var provider:angular.bootstrap.lightbox.ILightBoxProvider = {}; +provider.templateUrl = 'templateUrl'; +provider.calculateImageDimensionLimits = (dimensions:angular.bootstrap.lightbox.IImageDimensionParameter):angular.bootstrap.lightbox.IImageDimensionLimits=> { + return { + minWidth: 100, + minHeight: 100, + maxWidth: dimensions.windowWidth - 102, + maxHeight: dimensions.windowHeight - 136 + }; +}; +provider.calculateModalDimensions = (dimensions:angular.bootstrap.lightbox.IModalDimensionsParameter):angular.bootstrap.lightbox.IModalDimensions=> { + return { + width: Math.max(500, dimensions.imageDisplayWidth + 42), + height: Math.max(500, dimensions.imageDisplayHeight + 76) + }; + }; \ No newline at end of file diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts new file mode 100644 index 000000000..299967bdd --- /dev/null +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts @@ -0,0 +1,51 @@ +// Type definitions for angular-bootstrap-lightbox +// Project: https://github.com/compact/angular-bootstrap-lightbox +// Definitions by: Roland Zwaga +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module angular.bootstrap.lightbox { + + export interface ILightboxImageInfo { + url: string; + width: number; + height: number; + thumbUrl?: string; + caption?: string; + } + + export interface IImageDimensionLimits { + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; + } + + export interface IImageDimensionParameter { + windowWidth:number; + windowHeight:number; + imageWidth:number; + imageHeight:number; + } + + export interface IModalDimensionsParameter { + windowWidth:number; + windowHeight:number; + imageDisplayWidth:number; + imageDisplayHeight:number; + } + + export interface IModalDimensions { + width:number; + height:number; + } + + export interface ILightbox { + openModal(images:ILightboxImageInfo[], index:number):void; + } + + export interface ILightBoxProvider { + templateUrl:string; + calculateImageDimensionLimits:(dimensions:IImageDimensionParameter)=>IImageDimensionLimits; + calculateModalDimensions:(dimensions:IModalDimensionsParameter)=>IModalDimensions; + } +} \ No newline at end of file diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts new file mode 100644 index 000000000..a065d4b21 --- /dev/null +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +var scope: ng.IScope; +var hotkeyProvider: ng.hotkeys.HotkeysProvider; +var hotkeyObj: ng.hotkeys.Hotkey; + +hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); +hotkeyProvider.add(hotkeyObj); +hotkeyProvider.bindTo(scope); +hotkeyProvider.del("mod+s"); +hotkeyProvider.get("mod+s"); +hotkeyProvider.toggleCheatSheet(); + +hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); + +hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: function() {} + }); + diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts new file mode 100644 index 000000000..f209fbe08 --- /dev/null +++ b/angular-hotkeys/angular-hotkeys.d.ts @@ -0,0 +1,40 @@ +// Type definitions for angular-hotkeys +// Project: https://github.com/chieffancypants/angular-hotkeys +// Definitions by: Jason Zhao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ng.hotkeys { + + interface HotkeysProvider { + template: string; + includeCheatSheet: boolean; + cheatSheetHotkey: string; + cheatSheetDescription: string; + + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): void; + + add(hotkeyObj: ng.hotkeys.Hotkey): void; + + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained; + + del(combo: string): void; + + get(combo: string): ng.hotkeys.Hotkey; + + toggleCheatSheet(): void; + } + + interface HotkeysProviderChained { + add(combo: string, description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + + add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + } + + interface Hotkey { + combo: string; + description?: string; + callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + } +} diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 37c9e49bc..5ca9ecde4 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -153,21 +153,36 @@ function TestProtractor() { ptor.debugger(); + var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); + var promise: webdriver.promise.Promise; + promise = ptor.findElements(by.css('.class')); + promise = ptor.isElementPresent(by.css('.class')); + promise = ptor.isElementPresent(webElement); + ptor.clearMockModules(); ptor.addMockModule('name', 'script'); ptor.addMockModule('name', function() {}); + ptor.removeMockModule('name'); ptor.waitForAngular(); var elementFinder: protractor.ElementFinder; + var elementArrayFinder: protractor.ElementArrayFinder; elementFinder = ptor.element(by.id('ABC')); elementFinder = ptor.$('.class'); - var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); - - var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + elementArrayFinder = ptor.$$('.class'); var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); + ptor.setLocation('webaddress.com'); + + promise = ptor.get('webaddress.com'); + promise = ptor.get('webdaddress.com', 45); + ptor.refresh(); + ptor.refresh(45); + var navigation: webdriver.WebDriverNavigation = ptor.navigate(); + ptor.pause(); + ptor.pause(8080); } function TestElement() { @@ -180,6 +195,7 @@ function TestElementFinder() { var promise: webdriver.promise.Promise; promise = elementFinder.click(); + promise = elementFinder.allowAnimations('string'); promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); promise = elementFinder.getTagName(); promise = elementFinder.getCssValue('display'); @@ -195,19 +211,49 @@ function TestElementFinder() { promise = elementFinder.getOuterHtml(); promise = elementFinder.getInnerHtml(); promise = elementFinder.isElementPresent(by.id('id')); - promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); - promise = elementFinder.findElements(by.className('class')); - promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$('.class'); promise = elementFinder.$$('.class'); promise = elementFinder.evaluate('expression'); promise = elementFinder.isPresent(); var webElement: webdriver.WebElement; +} - webElement = elementFinder.$('.class'); - webElement = elementFinder.findElement(by.id('id')); - webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); - webElement = elementFinder.find(); +function TestElementArrayFinder() { + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); + var promise: webdriver.promise.Promise; + var elementFinder: protractor.ElementFinder; + + var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); + elementFinder = elementArrayFinder.get(42); + elementFinder = elementArrayFinder.first(); + elementFinder = elementArrayFinder.last(); + promise = elementArrayFinder.count(); + promise = elementArrayFinder.asElementFinders_(); + elementArrayFinder.each(function(element: protractor.ElementFinder){ + // nothing + }); + elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ + // nothing + }); + elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ + return element.getText().then((text: string) => { + return text === "foo"; + }); + }); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, ''); + elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ + //nothing + }); } // This function tests the angular specific locator strategies. @@ -216,29 +262,19 @@ function TestLocatorStrategies() { var webElement: webdriver.WebElement; // Protractor Specific Locators + protractor.By.addLocator('customLocator', 'script'); + protractor.By.addLocator('customLocator2', function(){ + // nothing + }); webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.select('select')); - webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); - webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.textarea('textarea')); webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); webElement = ptor.findElement(protractor.By.buttonText('buttonText')); webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); -} - -// This function tests the methods that were added to the base WebElement class -function TestWebElements() { - var ptor: protractor.Protractor = protractor.getInstance(); - - var webElement: protractor.WebElement; - var promise: webdriver.promise.Promise; - - webElement = ptor.findElement(by.id('id')).$('.class'); - promise = ptor.findElement(by.id('id')).$$('.class'); - promise = ptor.findElement(by.id('id')).evaluate('something'); - - webElement = webElement.findElement(by.id('id')).$('.class'); - promise = webElement.findElement(by.id('id')).$$('.class'); - promise = webElement.findElement(by.id('id')).evaluate('something'); + webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); + webElement = ptor.findElement(protractor.By.options('options')); } diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 3c3c0981f..2de49a0a4 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Protractor 0.17.0 +// Type definitions for Angular Protractor 1.0.0-rc4 // Project: https://github.com/angular/protractor // Definitions by: Bill Armstrong // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -25,71 +25,7 @@ declare module protractor { class CommandName extends webdriver.CommandName {} class Key extends webdriver.Key {} class UnhandledAlertError extends webdriver.UnhandledAlertError {} - - class WebElement extends webdriver.WebElement { - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - } + class WebElement extends webdriver.WebElement {} module command { class Command extends webdriver.Command {} @@ -273,13 +209,140 @@ declare module protractor { } //endregion - + /** + * Use as: element(locator) + * + * The ElementFinder can be treated as a WebElement for most purposes, in + * particular, you may perform actions (i.e. click, getText) on them as you + * would a WebElement. ElementFinders extend Promise, and once an action + * is performed on an ElementFinder, the latest result from the chain can be + * accessed using then. Unlike a WebElement, an ElementFinder will wait for + * angular to settle before performing finds or actions. + * + * ElementFinder can be used to build a chain of locators that is used to find + * an element. An ElementFinder does not actually attempt to find the element + * until an action is called, which means they can be set up in helper files + * before the page is available. + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementFinder} + */ interface Element { (locator: webdriver.Locator): ElementFinder; + + /** + * ElementArrayFinder is used for operations on an array of elements (as opposed + * to a single element). + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementArrayFinder} + */ all(locator: webdriver.Locator): ElementArrayFinder; } interface ElementFinder { + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} The descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} locator The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} The descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).isPresent() + * Determine whether the element is present on the page. + * + * @return {protractor.ElementFinder} Which resolves to whether the element is present on the page. + */ + isPresent(): webdriver.promise.Promise; + + /** + * Override for WebElement.prototype.isElementPresent so that protractor waits + * for Angular to settle before making the check. + * + * @see ElementFinder.isPresent + * @return {!webdriver.promise.Promise} which resolves to whether the element is present on the page. + */ + isElementPresent(locator: webdriver.Locator): webdriver.promise.Promise; + + /** + * Return this ElementFinder's locator. + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Use as: element(locator).getWebElement() + * Returns the WebElement represented by this ElementFinder. + * Throws the WebDriver error if the element doesn't exist. + * If index is null, it makes sure that there is only one underlying WebElement + * described by the chain of locators and issues a warning otherwise. + * If index is not null, it retrieves the WebElement specified by the index.. + * @return {webdriver.WebElement} The WebElement represented by the ElementFinder. + */ + getWebElement(): webdriver.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Determine if animation is allowed on the current element. + * @param {string} value + * + * @return {ElementFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: string): webdriver.promise.Promise; + + /** + * Access the underlying actionResult of ElementFinder. Implementation allows ElementFinder to be used as a webdriver.promise.Promise. + * @param {function(webdriver.promise.Promise)} fn Function which takes the value of the underlying actionResult. + * + * @return {webdriver.promise.Promise} Promise which contains the results of evaluating fn. + */ + then(fn: IThenFunction): webdriver.promise.Promise; + /** * Schedules a command to click on this element. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -460,113 +523,163 @@ declare module protractor { getInnerHtml(): webdriver.promise.Promise; /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - *

Note that JS locator searches cannot be restricted to a subtree of the - * DOM. All such searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether an element could be located on the page. + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol */ - isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Schedules a command to find all of the descendants of this element that match - * the given search criteria. - *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the elements. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of located {@link webdriver.WebElement}s. - */ - findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElement - * @return {!protractor.WebElement} - */ - $(selector: string): protractor.WebElement; - - /** - * Shortcut for querying the document directly with css. - * - * @param {string} selector a css selector - * @see webdriver.WebElement.findElements - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): webdriver.promise.Promise; - - /** - * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will - * be returned by the driver. Unlike other commands, this error cannot be - * suppressed. In other words, scheduling a command to find an element doubles - * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. - *

- * The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two - * statements are equivalent: - *

-         * var e1 = element.findElement(By.id('foo'));
-         * var e2 = element.findElement({id:'foo'});
-         * 
- *

- * Note that JS locator searches cannot be restricted to a subtree. All such - * searches are delegated to this instance's parent WebDriver. - * - * @param {webdriver.Locator|Object.} locator The locator - * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if - * using a JavaScript locator. Otherwise ignored. - * @return {protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. - */ - findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locator: any, ...var_args: any[]): protractor.WebElement; - - /** - * Evalates the input as if it were on the scope of the current element. - * @param {string} expression - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * evaluated expression. The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): webdriver.promise.Promise; - - find(): protractor.WebElement; - - isPresent(): webdriver.promise.Promise; + toWireValue(): webdriver.promise.Promise; } - interface ElementArrayFinder{ + interface IThenFunction { + (promiseResult: any): any; + } + + + interface ElementArrayFinder { + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {Array.} Array of WebElements represented by this ElementArrayFinder + */ + getWebElements(): webdriver.WebElement[]; + + /** + * Use as: element.all(locator).get(index) + * Get an element found by the locator by index. The index starts at 0. This does not actually retrieve the underlying element. + * + * @param {number} index Element index. + * + * @return {protractor.ElementFinder} Finder representing element at the given index + */ + get(index: number): protractor.ElementFinder; + + + /** + * Use as: element.all(locator).first() + * Get the first matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the first matching element + */ + first(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).last() + * Get the last matching element for the locator. This does not actually retrieve the underlying element. + * + * @return {Protractor.ElementFinder} Finder representing the last matching element + */ + last(): protractor.ElementFinder; + + /** + * Use as: element.all(locator).getWebElements() + * Returns the array of WebElements represented by this ElementArrayFinder. + * + * @return {!webdriver.promise.Promise} The array of WebElements represented by this ElementArrayFinder + */ count(): webdriver.promise.Promise; - get(index: number): protractor.WebElement; - first(): protractor.WebElement; - last(): protractor.WebElement; - then(fn: (value: any) => any): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).each(eachFunction) + * Calls the input function on each ElementFinder found by the locator. + * + * @param {function(ElementFinder)} fn Input function. + */ + each(fn: IEachFunction): void; + + /** + * Use as: element.all(locator).map(mapFunction) + * Apply a map function to each element found using the locator. The callback receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number)} mapFn Map function that will be applied to each element. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of values returned by the map function. + */ + map(mapFn: IMapFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).filter(filterFn) + * Apply a filter function to each element found using the locator. Returns promise of a new array with all elements that pass the filter function. The filter function receives the ElementFinder as the first argument and the index as a second arg. + * + * @param {function(ElementFinder, number): webdriver.promise.Promise} filterFn Filter function that will test if an element should be returned. filterFn should return a promise that resolves to a boolean. + * + * @return {!webdriver.promise.Promise} A promise that resolves to an array of ElementFinders that satisfy the filter function. + */ + filter(func: IFilterFunction): webdriver.promise.Promise; + + /** + * Use as: element.all(locator).reduce(reduceFn) + * Apply a reduce function against an accumulator and every element found using the locator (from left-to-right). + * The reduce function has to reduce every element into a single value (the accumulator). + * Returns promise of the accumulator. + * The reduce function receives the accumulator, current ElementFinder, the index, and the entire array of ElementFinders, respectively. + * + * @param {function(number, ElementFinder, number, Array.): webdriver.promise.Promise} reduceFn Reduce function that reduces every element into a single value. + * @param {*} initialValue Initial value of the accumulator. + * + * @return {!webdriver.promise.Promise} A promise that resolves to the final value of the accumulator. + */ + reduce(func: IReductionFunction, initialValue: any): webdriver.promise.Promise; + + /** + * Represents the ElementArrayFinder as an array of ElementFinders. + * + * @return {!webdriver.promise.Promise} Return a promise, which resolves to a list (array) + * of ElementFinders specified by the locator. + */ + asElementFinders_(): webdriver.promise.Promise; + + + /** + * Find the elements specified by the locator. The input function is passed + * to the resulting promise, which resolves to an array of ElementFinders. + * + * Use as: element.all(locator).then(thenFunction) + *

    + *
  • First
  • + *
  • Second
  • + *
  • Third
  • + *
+ * + * element.all(by.css('.items li')).then(function(arr) { + * expect(arr.length).toEqual(3); + * }); + * + * @param {function(Array.)} fn + * + * @type {webdriver.promise.Promise} a promise which will resolve to + * an array of ElementFinders matching the locator. + */ + then(fn: IElementArrayFinderThenFunction): webdriver.promise.Promise; + } + + interface IEachFunction { + (element: protractor.ElementFinder): void; + } + + interface IMapFunction { + (element: ElementFinder, index: number): any; + } + + interface IFilterFunction { + (element: ElementFinder, index: number): webdriver.promise.Promise; + } + + interface IReductionFunction { + (accumulator: any, element: protractor.ElementFinder, index?: number, array?: protractor.ElementFinder[]): webdriver.promise.Promise; + } + + interface IElementArrayFinderThenFunction { + (promiseResult: ElementFinder[]): any; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; } interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { @@ -587,69 +700,160 @@ declare module protractor { * Usage: * {{status}} * var status = element(by.binding('{{status}}')); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ binding(bindingDescriptor: string): webdriver.Locator; /** - * Usage: - * - * element(by.select("user")); + * Find an element by exact binding. + * + * {{ person.name }} + * + * {{person_phone|uppercase}} + * + * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person')).isPresent()).toBe(false); + * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); + * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); + * + * @param {string} bindingDescriptor + * @return {webdriver.Locator} */ - select(model: string): webdriver.Locator; + exactBinding(bindingDescriptor: string): webdriver.Locator; /** + * + * Find an element by ng-model expression. + * * Usage: - * - * element(by.selectedOption("user")); - */ - selectedOption(model: string): webdriver.Locator; - - /** - * @DEPRECATED - use 'model' instead. - * Usage: - * - * element(by.input('user')); - */ - input(model: string): webdriver.Locator; - - /** - * Usage: - * - * element(by.model('user')); + * + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + * @return {webdriver.Locator} */ model(model: string): webdriver.Locator; /** - * Usage: - * - * element(by.textarea("user")); - */ - textarea(model: string): webdriver.Locator; - - /** - * Usage: - *
- * {{cat.name}} - * {{cat.age}} - *
+ * Find a button by text. * - * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater("cat in pets").row(2)); - * // Returns the SPAN for the first cat's name. - * var firstCatName = element( - * by.repeater("cat in pets").row(1).column("{{cat.name}}")); - * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element( - * by.repeater("cat in pets").column("{{cat.age}}")); - * // Returns a promise that resolves to an array of WebElements containing - * // all rows of the repeater. - * var rows = element(by.repeater("cat in pets")); + * Usage: + * + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} */ - repeater(repeatDescriptor: string): webdriver.Locator; - buttonText(searchText: string): webdriver.Locator; + + /** + * Find a button by partial text. + * + * Usage: + * + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {webdriver.Locator} + */ partialButtonText(searchText: string): webdriver.Locator; + + /** + * Find elements inside an ng-repeat. + * + * Usage: + *
+ * {{cat.name}} + * {{cat.age}} + *
+ * + *
+ * {{$index}} + *
+ *
+ *

{{book.name}}

+ *

{{book.blurb}}

+ *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater('cat in pets').row(1)); + * + * // Returns the SPAN for the first cat's name. + * var firstCatName = element(by.repeater('cat in pets'). + * row(0).column('{{cat.name}}')); + * + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element.all( + * by.repeater('cat in pets').column('{{cat.age}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 pets rows resolves + * // to an array of 2 elements. + * var rows = element.all(by.repeater('cat in pets')); + * + * // Returns a promise that resolves to an array of WebElements containing all + * // the elements with a binding to the book's name. + * var divs = element.all(by.repeater('book in library').column('book.name')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // the DIVs for the second book. + * var bookInfo = element.all(by.repeater('book in library').row(1)); + * + * // Returns the H4 for the first book's name. + * var firstBookName = element(by.repeater('book in library'). + * row(0).column('{{book.name}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 books divs + * // resolves to an array of 4 elements. + * var divs = element.all(by.repeater('book in library')); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + /** + * Find elements by CSS which contain a certain string. + * + * @view + *
    + *
  • Dog
  • + *
  • Cat
  • + *
+ * + * @example + * // Returns the DIV for the dog, but not cat. + * var dog = element(by.cssContainingText('.pet', 'Dog')); + * + * @param cssSelector {string} + * @param searchText {string} + * @return {webdriver.Locator} + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * Usage: + * + * + * var allOptions = element.all(by.options('c for c in colors')); + * expect(allOptions.count()).toEqual(2); + * var firstOption = allOptions.first(); + * expect(firstOption.getText()).toEqual('red'); + * + * @param {string} optionsDescriptor ng-options expression. + * @return {webdriver.Locator} + */ + options(optionsDescriptor: string): webdriver.Locator; } var By: IProtractorLocatorStrategy; @@ -718,6 +922,43 @@ declare module protractor { //region Methods + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElement + * + * @param {webdriver.Locator} locator The locator used to find the element. + * @return {!webdriver.WebElement} + */ + findElement(locator: webdriver.Locator): protractor.WebElement; + + /** + * Waits for Angular to finish rendering before searching for elements. + * @see webdriver.WebDriver.findElements + * + * @param {webdriver.Locator} locator The locator used to find the elements. + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator): webdriver.promise.Promise; + + /** + * Tests if an element is present on the page. + * @see webdriver.WebDriver.isElementPresent + * @return {!webdriver.promise.Promise} A promise that will resolve to whether + * the element is present on the page. + */ + isElementPresent(locatorOrElement: webdriver.Locator): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any): webdriver.promise.Promise; + /** * Helper function for finding elements. * @@ -739,40 +980,71 @@ declare module protractor { */ $$(cssLocator: string): ElementArrayFinder; - /** - * Instruct webdriver to wait until Angular has finished rendering and has - * no outstanding $http calls before continuing. - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * scripts return value. - */ - waitForAngular(): webdriver.promise.Promise; - - /** - * Wrap a webdriver.WebElement with protractor specific functionality. - * - * @param {webdriver.WebElement} element - * @return {protractor.WebElement} the wrapped web element. - */ - wrapWebElement(element: webdriver.WebElement): protractor.WebElement; - /** * Add a module to load before Angular whenever Protractor.get is called. * Modules will be registered after existing modules already on the page, * so any module registered here will override preexisting modules with the same * name. * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. + * @param {string} name The name of the module to load or override. + * @param {string|Function} script The JavaScript to load the module. + * @param {...*} varArgs Any additional arguments will be provided to + * the script and may be referenced using the `arguments` object. */ - addMockModule(name: string, script: string): void; - addMockModule(name: string, script: any): void; + addMockModule(name: string, script: string, ...varArgs: any[]): void; + addMockModule(name: string, script: any, ...varArgs: any[]): void; /** * Clear the list of registered mock modules. */ clearMockModules(): void; + /** + * Remove a registered mock module. + * @param {!string} name The name of the module to remove. + */ + removeMockModule(name: string): void; + + /** + * See webdriver.WebDriver.get + * + * Navigate to the given destination and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {string} destination Destination URL. + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + + /** + * See webdriver.WebDriver.refresh + * + * Makes a full reload of the current page and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + refresh(opt_timeout?: number): void; + + /** + * Mixin navigation methods back into the navigation object so that + * they are invoked as before, i.e. driver.navigate().refresh() + */ + navigate(): webdriver.WebDriverNavigation; + + /** + * Browse to another page using in-page navigation. + * + * @param {string} url In page URL using the same syntax as $location.url() + * @returns {!webdriver.promise.Promise} A promise that will resolve once + * page has been changed. + */ + setLocation(url: string): webdriver.promise.Promise; + /** * Returns the current absolute url from AngularJS. */ @@ -799,43 +1071,14 @@ declare module protractor { debugger(): void; /** - * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned - * by the driver. Unlike other commands, this error cannot be suppressed. In - * other words, scheduling a command to find an element doubles as an assert - * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. + * Beta (unstable) pause function for debugging webdriver tests. Use + * browser.pause() in your test to enter the protractor debugger from that + * point in the control flow. + * Does not require changes to the command line (no need to add 'debug'). * - *

The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two statements - * are equivalent: - *

-         * var e1 = driver.findElement(By.id('foo'));
-         * var e2 = driver.findElement({id:'foo'});
-         * 
- * - *

When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual - * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!protractor.WebElement} A WebElement that can be used to issue - * commands against the located element. If the element is not found, the - * element will be invalidated and all scheduled commands aborted. + * @param {=number} opt_debugPort Optional port to use for the debugging process */ - findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; - findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + pause(opt_debugPort?: number): void; //endregion } @@ -863,9 +1106,19 @@ declare module protractor { } +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + declare var browser: protractor.Protractor; declare var by: protractor.IProtractorLocatorStrategy; declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; declare module 'protractor' { export = protractor; diff --git a/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts new file mode 100644 index 000000000..dfd413d0e --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0-tests.ts @@ -0,0 +1,244 @@ +/// + +function TestWebDriverExports() { + var abstractBuilder: protractor.AbstractBuilder = new protractor.AbstractBuilder(); + var baseAbstractBuilder: webdriver.AbstractBuilder = abstractBuilder; + + var button: protractor.Button = new protractor.Button(); + var baseButton: webdriver.Button = button; + + var key: string = protractor.Key.ADD; + var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); + + var driver: protractor.WebDriver = new protractor.Builder(). + withCapabilities(protractor.Capabilities.chrome()). + build(); + var baseDriver: webdriver.WebDriver = driver; + + var action: protractor.ActionSequence = new protractor.ActionSequence(driver); + var baseAction: webdriver.ActionSequence = action; + + var alert: protractor.Alert = new protractor.Alert(driver, 'Message'); + var baseAlert: webdriver.Alert = alert; + + var unhandledAlertError: protractor.UnhandledAlertError = new protractor.UnhandledAlertError('Message', alert); + var baseUnhandledAlertError: webdriver.UnhandledAlertError = unhandledAlertError; + + var browser: string = protractor.Browser.ANDROID; + + var builder: protractor.Builder = new protractor.Builder(); + var baseBuilder: webdriver.Builder = builder; + + var capability: string = protractor.Capability.BROWSER_NAME; + + var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); + var baseCapabilities: webdriver.Capabilities = capabilities; + + var commandName: string = protractor.CommandName.CLICK_ELEMENT; + + var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); + var baseCommand: webdriver.Command = command; + + var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); + var baseEventEmitter: webdriver.EventEmitter = eventEmitter; + + var firefoxDomExecutor: protractor.FirefoxDomExecutor = new protractor.FirefoxDomExecutor(); + var baseFirefoxDomExecutor: webdriver.FirefoxDomExecutor = firefoxDomExecutor; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); + var baseWebElement: webdriver.WebElement = webElement; + + var locator: protractor.Locator = new protractor.Locator('id', 'ABC'); + var baseLocator: webdriver.Locator = locator; + + var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); + var baseSession: webdriver.Session = session; + + locator = protractor.By.name('name'); + + // logging module + + var levelName: string = protractor.logging.LevelName.ALL; + var loggingType: string = protractor.logging.Type.CLIENT; + + var level: webdriver.logging.Level = protractor.logging.Level.ALL; + + var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); + var baseEntry: webdriver.logging.Entry = entry; + + level = protractor.logging.getLevel('DEBUG'); + + protractor.logging.Preferences = { a: 123 }; + + // promise module + + var promise: protractor.promise.Promise = new protractor.promise.Promise(); + var basePromise: webdriver.promise.Promise = promise; + + var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); + var baseDeferred: webdriver.promise.Deferred = deferred; + + var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); + var baseFlow: webdriver.promise.ControlFlow = flow; + + protractor.promise.asap(promise, function(value: any){ return true; }); + protractor.promise.asap(promise, function(value: any){}, function(err: any) { return 'ABC'; }); + + promise = protractor.promise.checkedNodeCall(function(err: any, value: any) { return 123; }); + + flow = protractor.promise.controlFlow(); + + promise = protractor.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { }); + + deferred = protractor.promise.defer(function() {}); + deferred = protractor.promise.defer(function(reason?: any) {}); + + promise = protractor.promise.delayed(123); + + promise = protractor.promise.fulfilled(); + promise = protractor.promise.fulfilled({a: 123}); + + promise = protractor.promise.fullyResolved({a: 123}); + + var isPromise: boolean = protractor.promise.isPromise('ABC'); + + promise = protractor.promise.rejected({a: 123}); + + protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = protractor.promise.when(promise, function(value: any) { return 123; }, function(err: Error) { return 123; }); + + // error module + + var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; + var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); + var baseError: webdriver.error.Error = error; + + // process module + + var isNative: boolean = protractor.process.isNative(); + var value: string; + + value = protractor.process.getEnv('name'); + value = protractor.process.getEnv('name', 'default'); + + protractor.process.setEnv('name', 'value'); + protractor.process.setEnv('name', 123); + +} + +function TestProtractor() { + var ptor: protractor.Protractor; + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + ptor = new protractor.Protractor(driver); + ptor = new protractor.Protractor(driver, 'baseUrl'); + ptor = new protractor.Protractor(driver, 'baseUrl', 'rootElement'); + ptor = protractor.getInstance(); + protractor.setInstance(ptor); + + ptor = protractor.wrapDriver(driver); + ptor = protractor.wrapDriver(driver, 'baseUrl'); + ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); + + ptor = browser; + + driver = ptor.driver; + var baseUrl: string = ptor.baseUrl; + var rootEl: string = ptor.rootEl; + var ignoreSynchronization: boolean = ptor.ignoreSynchronization; + var params: any = ptor.params; + + ptor.debugger(); + + ptor.clearMockModules(); + ptor.addMockModule('name', 'script'); + ptor.addMockModule('name', function() {}); + ptor.waitForAngular(); + + var elementFinder: protractor.ElementFinder; + + elementFinder = ptor.element(by.id('ABC')); + elementFinder = ptor.$('.class'); + + var elementArrayFinder: protractor.ElementArrayFinder = ptor.$$('.class'); + + var webElement: webdriver.WebElement = ptor.wrapWebElement(new webdriver.WebElement(driver, 'id')); + + var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); +} + +function TestElement() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); +} + +function TestElementFinder() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var promise: webdriver.promise.Promise; + + promise = elementFinder.click(); + promise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + promise = elementFinder.getTagName(); + promise = elementFinder.getCssValue('display'); + promise = elementFinder.getAttribute('atribute'); + promise = elementFinder.getText(); + promise = elementFinder.getSize(); + promise = elementFinder.getLocation(); + promise = elementFinder.isEnabled(); + promise = elementFinder.isSelected(); + promise = elementFinder.submit(); + promise = elementFinder.clear(); + promise = elementFinder.isDisplayed(); + promise = elementFinder.getOuterHtml(); + promise = elementFinder.getInnerHtml(); + promise = elementFinder.isElementPresent(by.id('id')); + promise = elementFinder.isElementPresent(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.findElements(by.className('class')); + promise = elementFinder.findElements(by.js('function(a, b, c) {}'), 1, 2, 3); + promise = elementFinder.$$('.class'); + promise = elementFinder.evaluate('expression'); + promise = elementFinder.isPresent(); + + var webElement: webdriver.WebElement; + + webElement = elementFinder.$('.class'); + webElement = elementFinder.findElement(by.id('id')); + webElement = elementFinder.findElement(by.js('function(a, b, c) {}'), 1, 2, 3); + webElement = elementFinder.find(); +} + +// This function tests the angular specific locator strategies. +function TestLocatorStrategies() { + var ptor: protractor.Protractor = protractor.getInstance(); + var webElement: webdriver.WebElement; + + // Protractor Specific Locators + webElement = ptor.findElement(protractor.By.binding('binding')); + webElement = ptor.findElement(protractor.By.select('select')); + webElement = ptor.findElement(protractor.By.selectedOption('selectedOptions')); + webElement = ptor.findElement(protractor.By.input('input')); + webElement = ptor.findElement(protractor.By.model('model')); + webElement = ptor.findElement(protractor.By.textarea('textarea')); + webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.buttonText('buttonText')); + webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); +} + +// This function tests the methods that were added to the base WebElement class +function TestWebElements() { + var ptor: protractor.Protractor = protractor.getInstance(); + + var webElement: protractor.WebElement; + var promise: webdriver.promise.Promise; + + webElement = ptor.findElement(by.id('id')).$('.class'); + promise = ptor.findElement(by.id('id')).$$('.class'); + promise = ptor.findElement(by.id('id')).evaluate('something'); + + webElement = webElement.findElement(by.id('id')).$('.class'); + promise = webElement.findElement(by.id('id')).$$('.class'); + promise = webElement.findElement(by.id('id')).evaluate('something'); +} diff --git a/angular-protractor/legacy/angular-protractor-0.17.0.d.ts b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts new file mode 100644 index 000000000..38458b493 --- /dev/null +++ b/angular-protractor/legacy/angular-protractor-0.17.0.d.ts @@ -0,0 +1,906 @@ +// Type definitions for Angular Protractor 0.17.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module protractor { + //region Wrapped webdriver Items + + class AbstractBuilder extends webdriver.AbstractBuilder {} + class ActionSequence extends webdriver.ActionSequence {} + class Alert extends webdriver.Alert {} + class Builder extends webdriver.Builder {} + class Button extends webdriver.Button {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class FirefoxDomExecutor extends webdriver.FirefoxDomExecutor {} + class Locator extends webdriver.Locator {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class Browser extends webdriver.Browser {} + class Capability extends webdriver.Capability {} + class CommandName extends webdriver.CommandName {} + class Key extends webdriver.Key {} + class UnhandledAlertError extends webdriver.UnhandledAlertError {} + + class WebElement extends webdriver.WebElement { + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + } + + module command { + class Command extends webdriver.Command {} + class CommandName extends webdriver.CommandName {} + } + + module error { + class Error extends webdriver.error.Error {} + class ErrorCode extends webdriver.error.ErrorCode {} + } + + module events { + class EventEmitter extends webdriver.EventEmitter {} + } + + module logging { + var Preferences: any; + + class LevelName extends webdriver.logging.LevelName {} + class Type extends webdriver.logging.Type {} + class Level extends webdriver.logging.Level {} + class Entry extends webdriver.logging.Entry {} + + function getLevel(nameOrValue: string): webdriver.logging.Level; + function getLevel(nameOrValue: number): webdriver.logging.Level; + } + + module promise { + class Promise extends webdriver.promise.Promise {} + class Deferred extends webdriver.promise.Deferred {} + class ControlFlow extends webdriver.promise.ControlFlow {} + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => any): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Creates a new deferred object. + * @param {Function=} opt_canceller Function to call when cancelling the + * computation of this instance's value. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(opt_canceller?: any): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: any): webdriver.promise.Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: (error: any, value: any) => any): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: any, opt_callback?: (value: any) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@code webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: (value: any) => any, opt_errback?: (error: any) => any): void; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + + } + + module process { + + /** + * Queries for a named environment variable. + * @param {string} name The name of the environment variable to look up. + * @param {string=} opt_default The default value if the named variable is not + * defined. + * @return {string} The queried environment variable. + */ + function getEnv(name: string, opt_default?: string): string; + + /** + * @return {boolean} Whether the current process is Node's native process + * object. + */ + function isNative(): boolean; + + /** + * Sets an environment value. If the new value is either null or undefined, the + * environment variable will be cleared. + * @param {string} name The value to set. + * @param {*} value The new value; will be coerced to a string. + */ + function setEnv(name: string, value: any): void; + + } + + //endregion + + interface Element { + (locator: webdriver.Locator): ElementFinder; + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder { + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

+ * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

    + *
  • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
  • + *
  • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
  • + *
  • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
  • + *
+ * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • "class" + *
  • "readonly" + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + *

Note that JS locator searches cannot be restricted to a subtree of the + * DOM. All such searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether an element could be located on the page. + */ + isElementPresent(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that match + * the given search criteria. + *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the elements. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {!webdriver.promise.Promise} A promise that will be resolved with an + * array of located {@link webdriver.WebElement}s. + */ + findElements(locator: webdriver.Locator, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElement + * @return {!protractor.WebElement} + */ + $(selector: string): protractor.WebElement; + + /** + * Shortcut for querying the document directly with css. + * + * @param {string} selector a css selector + * @see webdriver.WebElement.findElements + * @return {!webdriver.promise.Promise} A promise that will be resolved to an + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): webdriver.promise.Promise; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + *

+ * The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two + * statements are equivalent: + *

+         * var e1 = element.findElement(By.id('foo'));
+         * var e2 = element.findElement({id:'foo'});
+         * 
+ *

+ * Note that JS locator searches cannot be restricted to a subtree. All such + * searches are delegated to this instance's parent WebDriver. + * + * @param {webdriver.Locator|Object.} locator The locator + * strategy to use when searching for the element. + * @param {...} var_args Arguments to pass to {@code WebDriver#executeScript} if + * using a JavaScript locator. Otherwise ignored. + * @return {protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locator: any, ...var_args: any[]): protractor.WebElement; + + /** + * Evalates the input as if it were on the scope of the current element. + * @param {string} expression + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * evaluated expression. The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): webdriver.promise.Promise; + + /** + * Use as: element(locator).element(locator) + * Calls to element may be chained to find elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementFinder} the descendent element found by the locator + */ + element(locator: webdriver.Locator): protractor.ElementFinder; + + /** + * Use as: element(locator).all(locator) + * Calls to element may be chained to find an array of elements within a parent. + * + * @param {webdriver.Locator} The locator that will be used to find descendents. + * + * @return {protractor.ElementArrayFinder} the descendent elements found by the locator + */ + all(locator: webdriver.Locator): protractor.ElementArrayFinder; + + find(): protractor.WebElement; + + isPresent(): webdriver.promise.Promise; + } + + interface ElementArrayFinder{ + count(): webdriver.promise.Promise; + get(index: number): protractor.WebElement; + first(): protractor.WebElement; + last(): protractor.WebElement; + then(fn: (value: any) => any): webdriver.promise.Promise; + } + + class LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + } + + class RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; + } + + interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.()). + * + * @param {string} name + * @param {function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that begins with the element scoping the search, and then + * contains any args passed into the locator. It should return + * an array of elements. + */ + addLocator(name: string, script: any): void; + + /** + * Usage: + * {{status}} + * var status = element(by.binding('{{status}}')); + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.select("user")); + */ + select(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.selectedOption("user")); + */ + selectedOption(model: string): webdriver.Locator; + + /** + * @DEPRECATED - use 'model' instead. + * Usage: + * + * element(by.input('user')); + */ + input(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.model('user')); + */ + model(model: string): webdriver.Locator; + + /** + * Usage: + * + * element(by.textarea("user")); + */ + textarea(model: string): webdriver.Locator; + + /** + * Usage: + *

+ * {{cat.name}} + * {{cat.age}} + *
+ * + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater("cat in pets").row(2)); + * // Returns the SPAN for the first cat's name. + * var firstCatName = element( + * by.repeater("cat in pets").row(1).column("{{cat.name}}")); + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element( + * by.repeater("cat in pets").column("{{cat.age}}")); + * // Returns a promise that resolves to an array of WebElements containing + * // all rows of the repeater. + * var rows = element(by.repeater("cat in pets")); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + buttonText(searchText: string): webdriver.Locator; + + partialButtonText(searchText: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + class Protractor extends webdriver.WebDriver { + + //region Constructors + + /** + * @param {webdriver.WebDriver} webdriver + * @param {string=} opt_baseUrl A base URL to run get requests against. + * @param {string=body} opt_rootElement Selector element that has an ng-app in + * scope. + * @constructor + */ + constructor(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string); + + //endregion + + //region Properties + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + //endregion + + //region Methods + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Helper function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(cssLocator: string): ElementFinder; + + /** + * Helper function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(cssLocator: string): ElementArrayFinder; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Wrap a webdriver.WebElement with protractor specific functionality. + * + * @param {webdriver.WebElement} element + * @return {protractor.WebElement} the wrapped web element. + */ + wrapWebElement(element: webdriver.WebElement): protractor.WebElement; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + */ + addMockModule(name: string, script: string): void; + addMockModule(name: string, script: any): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): webdriver.promise.Promise; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for find an element may either be a + * {@code webdriver.Locator} object, or a simple JSON object whose sole key + * is one of the accepted locator strategies, as defined by + * {@code webdriver.Locator.Strategy}. For example, the following two statements + * are equivalent: + *

+         * var e1 = driver.findElement(By.id('foo'));
+         * var e2 = driver.findElement({id:'foo'});
+         * 
+ * + *

When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The + * locator strategy to use when searching for the element, or the actual + * DOM element to be located by the server. + * @param {...} var_args Arguments to pass to {@code #executeScript} if using a + * JavaScript locator. Otherwise ignored. + * @return {!protractor.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: webdriver.Locator, ...var_args: any[]): protractor.WebElement; + findElement(locatorOrElement: any, ...var_args: any[]): protractor.WebElement; + + //endregion + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; + + /** + * Set a singleton instance of protractor. + * @param {Protractor} ptor + */ + function setInstance(ptor: Protractor): void; + + /** + * Get the singleton instance. + * @return {Protractor} + */ + function getInstance(): Protractor; + +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +declare var browser: protractor.Protractor; +declare var by: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssSelectorHelper; + +declare module 'protractor' { + export = protractor; +} diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 313ef8635..4b8da8449 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -33,13 +33,14 @@ declare module ng.translate { } interface ITranslateService { - (key: string, ...params: string[]): ng.IPromise; + (translationId: string, interpolateParams?: any, interpolationId?: string): ng.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; fallbackLanguage(langKey?: string): string; fallbackLanguage(langKey?: string[]): string; instant(translationId: string, interpolateParams?: any, interpolationId?: string): string; - instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string; + instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string }; isPostCompilingEnabled(): boolean; preferredLanguage(): string; proposedLanguage(): string; diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index 081d35723..005bf8b90 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -11,8 +11,9 @@ declare module ng.ui { name?: string; template?: any; templateUrl?: any; - templateProvider?: () => string; + templateProvider?: any; controller?: any; + controllerAs?: string; controllerProvider?: any; resolve?: {}; url?: string; diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 6db753e1f..2591c006e 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -33,9 +33,7 @@ declare module ng { inject(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works // see http://docs.angularjs.org/api/angular.mock.module - module(...modules: string[]): any; - module(...modules: Function[]): any; - module(modules: Object): any; + module(...modules: any[]): any; // see http://docs.angularjs.org/api/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 37dae22f4..0627f80be 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -7,27 +7,27 @@ * (c) 2012 Witold Szczerba * License: MIT */ -angular.module('http-auth-interceptor', []) - .provider('authService', function () { - /** - * Holds all the requests which failed due to 401 response, - * so they can be re-requested in future, once login is completed. - */ - var buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; +class AuthService { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; - /** - * Required by HTTP interceptor. - * Function is attached to provider to be invisible for regular users of this service. - */ - this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) { - buffer.push({ - config: config, - deferred: deferred - }); - } + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + this.buffer.push({ + config: config, + deferred: deferred + }); + } - this.$get = ['$rootScope', '$injector', function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + $get = [ + '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { var $http: ng.IHttpService; //initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); @@ -36,20 +36,25 @@ angular.module('http-auth-interceptor', []) }); } function retryAll() { - for (var i = 0; i < buffer.length; ++i) { - retry(buffer[i].config, buffer[i].deferred); + for (var i = 0; i < this.buffer.length; ++i) { + retry(this.buffer[i].config, this.buffer[i].deferred); } - buffer = []; + this.buffer = []; } - return { + return { loginConfirmed: function () { $rootScope.$broadcast('event:auth-loginConfirmed'); retryAll(); } } - }] - }) + } + ]; +} + +angular.module('http-auth-interceptor', []) + + .provider('authService', AuthService) /** * $http interceptor. @@ -95,6 +100,7 @@ module HttpAndRegularPromiseTests { theAnswer: number; letters: string[]; snack: string; + nothing?: string; } var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { @@ -139,6 +145,12 @@ module HttpAndRegularPromiseTests { dPromise.then((snack: string) => { $scope.snack = snack; }); + + // $q.when may be called without arguments + var ePromise: ng.IPromise = $q.when(); + ePromise.then(() => { + $scope.nothing = "really nothing"; + }); } // Test that we can pass around a type-checked success/error Promise Callback @@ -176,7 +188,8 @@ mod.factory(My.Namespace); mod.filter('name', function ($scope: ng.IScope) { }) mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) mod.filter(My.Namespace); -mod.provider('name', function ($scope: ng.IScope) { }) +mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', TestProvider); mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) mod.provider(My.Namespace); mod.service('name', function ($scope: ng.IScope) { }) @@ -189,6 +202,13 @@ mod.value('name', 23); mod.value('name', "23"); mod.value(My.Namespace); +class TestProvider implements ng.IServiceProvider { + constructor(private $scope: ng.IScope) { + } + + $get() { + } +} // Promise signature tests var foo: ng.IPromise; @@ -211,11 +231,11 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + //Try a promise var y: ng.IPromise; - return y; + return y; }).then((x) => { - // x is infered to be a number, which is the resolved value of a promise + // x is infered to be a number, which is the resolved value of a promise x.toFixed(); }); @@ -231,6 +251,15 @@ httpFoo.then((x) => { }); +function test_angular_forEach() { + var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + var log: string[] = []; + angular.forEach(values, function (value, key) { + this.push(key + ': ' + value); + }, log); + //expect(log).toEqual(['name: misko', 'gender: male']); +} + // angular.element() tests var element = angular.element("div.myApp"); var scope: ng.IScope = element.scope(); @@ -251,3 +280,323 @@ test_IAttributes({ }, $attr: {} }); + +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: ng.IAugmentedJQuery) { + return { + post: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective(); + } + + link(scope: ng.IScope) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: ng.IAugmentedJQuery) { + return { + pre: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective2(); + } + + link(scope: ng.IScope) { + + } +} + +angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance); + +// test from https://docs.angularjs.org/guide/directive +angular.module('docsSimpleDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); + +angular.module('docsTemplateUrlDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsRestrictDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsScopeProblemExample', []) + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsIsolateScopeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); + +angular.module('docsIsolationExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); + +angular.module('docsTimeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { + + return { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { + var format: any, + timeoutId: any; + + function updateTime() { + element.text(dateFilter(new Date(), format)); + } + + scope.$watch(attrs['myCurrentTime'], function (value: any) { + format = value; + updateTime(); + }); + + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); + + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); + +angular.module('docsTransclusionDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); + +angular.module('docsTransclusionExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) { + scope['name'] = 'Jeff'; + } + }; + }); + +angular.module('docsIsoFnBindExample', []) + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); + +angular.module('dragModule', []) + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; + + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); + + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); + +angular.module('docsTabsExample', []) + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: ng.IScope) { + var panes: any = $scope['panes'] = []; + + $scope['select'] = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; + + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope['select'](pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); + +interface copyExampleUser { + name?: string; + email?: string; + gender?: string; +} + +interface copyExampleScope { + + user: copyExampleUser; + master: copyExampleUser; + update: (copyExampleUser: copyExampleUser) => any; + reset: () => any; +} + +angular.module('copyExample', []) + .controller('ExampleController', ['$scope', function ($scope: copyExampleScope) { + $scope.master = { }; + + $scope.update = function (user) { + // Example with 1 argument + $scope.master = angular.copy(user); + }; + + $scope.reset = function () { + // Example with 2 arguments + angular.copy($scope.master, $scope.user); + }; + + $scope.reset(); + }]); \ No newline at end of file diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index d6b649a33..0fc44d976 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular JS 1.2+ +// Type definitions for Angular JS 1.3+ // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -18,6 +18,15 @@ interface Function { /////////////////////////////////////////////////////////////////////////////// declare module ng { + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new(...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + // All service providers extend this interface interface IServiceProvider { $get: any; @@ -33,11 +42,55 @@ declare module ng { bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; bootstrap(element: Element, modules?: any[]): auto.IInjectorService; bootstrap(element: Document, modules?: any[]): auto.IInjectorService; - copy(source: any, destination?: any): any; + + /** + * Creates a deep copy of source, which should be an object or an array. + * + * - If no destination is supplied, a copy of the object or array is created. + * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. + * - If source is not an object or array (inc. null and undefined), source is returned. + * - If source is identical to 'destination' an exception will be thrown. + * + * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined. + * @param destination Destination into which the source is copied. If provided, must be of the same type as source. + */ + copy(source: T, destination?: T): T; + element: IAugmentedJQueryStatic; equals(value1: any, value2: any): boolean; extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + fromJson(json: string): any; identity(arg?: any): any; injector(modules?: any[]): auto.IInjectorService; @@ -56,7 +109,7 @@ declare module ng { * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. - * + * * @param name The name of the module to create or retrieve. * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. * @param configFn Optional configuration function for the module. @@ -88,19 +141,19 @@ declare module ng { animation(object: Object): IModule; /** * Use this method to register work which needs to be performed on module loading. - * + * * @param configFn Execute this function on module load. Useful for service configuration. */ config(configFn: Function): IModule; /** * Use this method to register work which needs to be performed on module loading. - * + * * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. */ config(inlineAnnotatedFunction: any[]): IModule; /** * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * + * * @param name The name of the constant. * @param value The constant value. */ @@ -108,36 +161,36 @@ declare module ng { constant(object: Object): IModule; /** * The $controller service is used by Angular to create new controllers. - * + * * This provider allows controller registration via the register method. - * + * * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). */ controller(name: string, controllerConstructor: Function): IModule; /** * The $controller service is used by Angular to create new controllers. - * + * * This provider allows controller registration via the register method. - * + * * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). */ controller(name: string, inlineAnnotatedConstructor: any[]): IModule; controller(object : Object): IModule; - directive(name: string, directiveFactory: Function): IModule; + directive(name: string, directiveFactory: IDirectiveFactory): IModule; directive(name: string, inlineAnnotatedFunction: any[]): IModule; directive(object: Object): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * + * * @param name The name of the instance. * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). */ factory(name: string, $getFn: Function): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. - * + * * @param name The name of the instance. * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). */ @@ -146,9 +199,10 @@ declare module ng { filter(name: string, filterFactoryFunction: Function): IModule; filter(name: string, inlineAnnotatedFunction: any[]): IModule; filter(object: Object): IModule; - provider(name: string, serviceProviderConstructor: Function): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; provider(name: string, inlineAnnotatedConstructor: any[]): IModule; - provider(name: string, providerObject: auto.IProvider): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; provider(object: Object): IModule; /** * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. @@ -211,21 +265,31 @@ declare module ng { $attr: Object; } - /////////////////////////////////////////////////////////////////////////// - // FormController - // see http://docs.angularjs.org/api/ng.directive:form.FormController - /////////////////////////////////////////////////////////////////////////// + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + $pristine: boolean; $dirty: boolean; $valid: boolean; $invalid: boolean; + $submitted: boolean; $error: any; $addControl(control: ng.INgModelController): void; $removeControl(control: ng.INgModelController): void; $setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void; $setDirty(): void; $setPristine(): void; + $commitViewValue(): void; + $rollbackViewValue(): void; + $setSubmitted(): void; } /////////////////////////////////////////////////////////////////////////// @@ -238,19 +302,38 @@ declare module ng { // Documentation states viewValue and modelValue to be a string but other // types do work and it's common to use them. $setViewValue(value: any): void; + $validate(): void; + $setTouched(): void; + $setUntouched(): void; + $rollbackViewValue(): void; + $commitViewValue(revalidate?: boolean): void; + $isEmpty(value: any): boolean; + $viewValue: any; $modelValue: any; $parsers: IModelParser[]; $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; $error: any; + $name: string; + + $touched: boolean; + $untouched: boolean; + + $validators: IModelValidators; + $pristine: boolean; $dirty: boolean; $valid: boolean; $invalid: boolean; } + interface IModelValidators { + [index: string]: (...args: any[]) => boolean; + } + interface IModelParser { (value: any): any; } @@ -259,11 +342,15 @@ declare module ng { (value: any): any; } + interface IModelViewChangeListener { + (): void; + } + /////////////////////////////////////////////////////////////////////////// - // Scope - // see http://docs.angularjs.org/api/ng.$rootScope.Scope + // Scope and RootScope + // see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and http://docs.angularjs.org/api/ng.$rootScope /////////////////////////////////////////////////////////////////////////// - interface IScope { + interface IRootScopeService { $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; @@ -300,14 +387,19 @@ declare module ng { $parent: IScope; $root: IRootScopeService; + this: IRootScopeService; - $id: string; + $id: number; // Hidden members $$isolateBindings: any; $$phase: any; } + interface IScope extends IRootScopeService { + [index: string]: any; + } + interface IAngularEvent { targetScope: IScope; currentScope: IScope; @@ -527,17 +619,17 @@ declare module ng { interface IQService { /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * + * * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * + * * @param promises An array or hash of promises. */ all(promises: IPromise[]): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. - * + * * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * + * * @param promises An array or hash of promises. */ all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any }>; @@ -547,24 +639,30 @@ declare module ng { defer(): IDeferred; /** * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. - * + * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. - * + * * @param reason Constant, message, exception or an object representing the rejection reason. */ reject(reason?: any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(value: IPromise): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. - * + * * @param value Value or a promise */ when(value: T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; } interface IPromise { @@ -649,7 +747,7 @@ declare module ng { aHrefSanitizationWhitelist(): RegExp; aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; - + imgSrcSanitizationWhitelist(): RegExp; imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; } @@ -689,7 +787,7 @@ declare module ng { } /** - * HttpService + * HttpService * see http://docs.angularjs.org/api/ng/service/$http */ interface IHttpService { @@ -700,7 +798,7 @@ declare module ng { /** * Shortcut method to perform GET request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -708,7 +806,7 @@ declare module ng { /** * Shortcut method to perform DELETE request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -716,7 +814,7 @@ declare module ng { /** * Shortcut method to perform HEAD request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -724,7 +822,7 @@ declare module ng { /** * Shortcut method to perform JSONP request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param config Optional configuration object */ @@ -732,7 +830,7 @@ declare module ng { /** * Shortcut method to perform POST request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param data Request content * @param config Optional configuration object @@ -741,7 +839,7 @@ declare module ng { /** * Shortcut method to perform PUT request. - * + * * @param url Relative or absolute URL specifying the destination of the request * @param data Request content * @param config Optional configuration object @@ -761,12 +859,12 @@ declare module ng { /** * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage + * see http://docs.angularjs.org/api/ng/service/$http#usage */ interface IRequestShortcutConfig { /** * {Object.} - * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. */ params?: any; @@ -797,7 +895,7 @@ declare module ng { withCredentials?: boolean; /** - * {string|Object} + * {string|Object} * Data to be sent as the request message data. */ data?: any; @@ -828,7 +926,7 @@ declare module ng { /** * Object describing the request to be made and how it should be processed. - * see http://docs.angularjs.org/api/ng/service/$http#usage + * see http://docs.angularjs.org/api/ng/service/$http#usage */ interface IRequestConfig extends IRequestShortcutConfig { /** @@ -904,12 +1002,6 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface ITemplateCacheService extends ICacheObject {} - /////////////////////////////////////////////////////////////////////////// - // RootScopeService - // see http://docs.angularjs.org/api/ng.$rootScope - /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope {} - /////////////////////////////////////////////////////////////////////////// // SCEService // see http://docs.angularjs.org/api/ng.$sce @@ -969,21 +1061,38 @@ declare module ng { // and http://docs.angularjs.org/guide/directive /////////////////////////////////////////////////////////////////////////// - interface IDirective{ - compile?: - (templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - transclude: ITranscludeFunction - ) => any; - controller?: any; - controllerAs?: string; - link?: - (scope: IScope, + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirectiveLinkFn { + ( + scope: IScope, instanceElement: IAugmentedJQuery, instanceAttributes: IAttributes, controller: any, transclude: ITranscludeFunction - ) => void; + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + link?: IDirectiveLinkFn; name?: string; priority?: number; replace?: boolean; @@ -1047,9 +1156,6 @@ declare module ng { // AUTO module (angular.js) /////////////////////////////////////////////////////////////////////////// export module auto { - interface IProvider { - $get: any; - } /////////////////////////////////////////////////////////////////////// // InjectorService @@ -1059,7 +1165,7 @@ declare module ng { annotate(fn: Function): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string): any; - has(name: string): boolean; + has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): any; invoke(inlineAnnotatedFunction: any[]): any; invoke(func: Function, context?: any, locals?: any): any; @@ -1075,7 +1181,7 @@ declare module ng { // constant(name: string, value: any): any; /** * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. - * + * * @param name The name of the constant. * @param value The constant value. */ @@ -1083,19 +1189,19 @@ declare module ng { /** * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * + * * @param name The name of the service to decorate. * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * + * * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, decorator: Function): void; /** * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. - * + * * @param name The name of the service to decorate. * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: - * + * * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, inlineAnnotatedFunction: any[]): void; diff --git a/angularjs/legacy/angular-1.2-tests.ts b/angularjs/legacy/angular-1.2-tests.ts new file mode 100644 index 000000000..d0f60609a --- /dev/null +++ b/angularjs/legacy/angular-1.2-tests.ts @@ -0,0 +1,571 @@ +/// + +// issue: https://github.com/borisyankov/DefinitelyTyped/issues/369 +// https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js +/** + * @license HTTP Auth Interceptor Module for AngularJS + * (c) 2012 Witold Szczerba + * License: MIT + */ + +class AuthService { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; + + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { + this.buffer.push({ + config: config, + deferred: deferred + }); + } + + $get = [ + '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + var $http: ng.IHttpService; //initialized later because of circular dependency problem + function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { + $http = $http || $injector.get('$http'); + $http(config).then(function (response) { + deferred.resolve(response); + }); + } + function retryAll() { + for (var i = 0; i < this.buffer.length; ++i) { + retry(this.buffer[i].config, this.buffer[i].deferred); + } + this.buffer = []; + } + + return { + loginConfirmed: function () { + $rootScope.$broadcast('event:auth-loginConfirmed'); + retryAll(); + } + } + } + ]; +} + +angular.module('http-auth-interceptor', []) + + .provider('authService', AuthService) + +/** + * $http interceptor. + * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. + */ + .config(['$httpProvider', 'authServiceProvider', function ($httpProvider: ng.IHttpProvider, authServiceProvider: any) { + + var interceptor = ['$rootScope', '$q', function ($rootScope: ng.IScope, $q: ng.IQService) { + function success(response: ng.IHttpPromiseCallbackArg) { + return response; + } + + function error(response: ng.IHttpPromiseCallbackArg) { + if (response.status === 401) { + var deferred = $q.defer(); + authServiceProvider.pushToBuffer(response.config, deferred); + $rootScope.$broadcast('event:auth-loginRequired'); + return deferred.promise; + } + // otherwise + return $q.reject(response); + } + + return function (promise: ng.IHttpPromise) { + return promise.then(success, error); + } + + }]; + $httpProvider.responseInterceptors.push(interceptor); + }]); + + +module HttpAndRegularPromiseTests { + interface Person { + firstName: string; + lastName: string; + } + + interface ExpectedResponse extends Person { } + + interface SomeControllerScope extends ng.IScope { + person: Person; + theAnswer: number; + letters: string[]; + snack: string; + nothing?: string; + } + + var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { + $http.get("http://somewhere/some/resource") + .success((data: ExpectedResponse) => { + $scope.person = data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would type check + $scope.person = response.data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would NOT type check + $scope.person = response.data; + }); + + var aPromise: ng.IPromise = $q.when({ firstName: "Jack", lastName: "Sparrow" }); + aPromise.then((person: Person) => { + $scope.person = person; + }); + + var bPromise: ng.IPromise = $q.when(42); + bPromise.then((answer: number) => { + $scope.theAnswer = answer; + }); + + var cPromise: ng.IPromise = $q.when(["a", "b", "c"]); + cPromise.then((letters: string[]) => { + $scope.letters = letters; + }); + + // When $q.when is passed an IPromise, it returns an IPromise + var dPromise: ng.IPromise = $q.when($q.when("ALBATROSS!")); + dPromise.then((snack: string) => { + $scope.snack = snack; + }); + + // $q.when may be called without arguments + var ePromise: ng.IPromise = $q.when(); + ePromise.then(() => { + $scope.nothing = "really nothing"; + }); + } + + // Test that we can pass around a type-checked success/error Promise Callback + var anotherController: Function = ($scope: SomeControllerScope, $http: + ng.IHttpService, $q: ng.IQService) => { + + var buildFooData: Function = () => 42; + + var doFoo: Function = (callback: ng.IHttpPromiseCallback) => { + $http.get('/foo', buildFooData()) + .success(callback); + } + + doFoo((data: any) => console.log(data)); + } +} + +// Test for AngularJS Syntax + +module My.Namespace { + export var x: any; // need to export something for module to kick in +} + +// IModule Registering Test +var mod = angular.module('tests', []); +mod.controller('name', function ($scope: ng.IScope) { }) +mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.controller(My.Namespace); +mod.directive('name', function ($scope: ng.IScope) { }) +mod.directive('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.directive(My.Namespace); +mod.factory('name', function ($scope: ng.IScope) { }) +mod.factory('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.factory(My.Namespace); +mod.filter('name', function ($scope: ng.IScope) { }) +mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.filter(My.Namespace); +mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', TestProvider); +mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.provider(My.Namespace); +mod.service('name', function ($scope: ng.IScope) { }) +mod.service('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.service(My.Namespace); +mod.constant('name', 23); +mod.constant('name', "23"); +mod.constant(My.Namespace); +mod.value('name', 23); +mod.value('name', "23"); +mod.value(My.Namespace); + +class TestProvider implements ng.IServiceProvider { + constructor(private $scope: ng.IScope) { + } + + $get() { + } +} + +// Promise signature tests +var foo: ng.IPromise; +foo.then((x) => { + // x is inferred to be a number + return "asdf"; +}).then((x) => { + // x is inferred to be string + x.length; + return 123; +}).then((x) => { + // x is infered to be a number + x.toFixed(); + return; +}).then((x) => { + // x is infered to be void + // Typescript will prevent you to actually use x as a local variable + // Try object: + return { a: 123 }; +}).then((x) => { + // Object is inferred here + x.a = 123; + //Try a promise + var y: ng.IPromise; + return y; +}).then((x) => { + // x is infered to be a number, which is the resolved value of a promise + x.toFixed(); +}); + + +var httpFoo: ng.IHttpPromise; +httpFoo.then((x) => { + // When returning a promise the generic type must be inferred. + var innerPromise : ng.IPromise; + return innerPromise; +}).then((x) => { + // must still be number. + x.toFixed(); +}); + + +function test_angular_forEach() { + var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + var log: string[] = []; + angular.forEach(values, function (value, key) { + this.push(key + ': ' + value); + }, log); + //expect(log).toEqual(['name: misko', 'gender: male']); +} + +// angular.element() tests +var element = angular.element("div.myApp"); +var scope: ng.IScope = element.scope(); +var isolateScope: ng.IScope = element.isolateScope(); + + + +function test_IAttributes(attributes: ng.IAttributes){ + return attributes; +} + +test_IAttributes({ + $addClass: function (classVal){}, + $removeClass: function(classVal){}, + $set: function(key, value){}, + $observe: function(name, fn){ + return fn; + }, + $attr: {} +}); + +class SampleDirective implements ng.IDirective { + public restrict = 'A'; + name = 'doh'; + + compile(templateElement: ng.IAugmentedJQuery) { + return { + post: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective(); + } + + link(scope: ng.IScope) { + + } +} + +class SampleDirective2 implements ng.IDirective { + public restrict = 'EAC'; + + compile(templateElement: ng.IAugmentedJQuery) { + return { + pre: this.link + }; + } + + static instance():ng.IDirective { + return new SampleDirective2(); + } + + link(scope: ng.IScope) { + + } +} + +angular.module('SameplDirective', []).directive('sampleDirective', SampleDirective.instance).directive('sameplDirective2', SampleDirective2.instance); + +// test from https://docs.angularjs.org/guide/directive +angular.module('docsSimpleDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + template: 'Name: {{customer.name}} Address: {{customer.address}}' + }; + }); + +angular.module('docsTemplateUrlDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsRestrictDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsScopeProblemExample', []) + .controller('NaomiController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Naomi', + address: '1600 Amphitheatre' + }; + }]) + .controller('IgorController', ['$scope', function($scope: any) { + $scope.customer = { + name: 'Igor', + address: '123 Somewhere' + }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + templateUrl: 'my-customer.html' + }; + }); + +angular.module('docsIsolateScopeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.igor = { name: 'Igor', address: '123 Somewhere' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-iso.html' + }; + }); + +angular.module('docsIsolationExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' }; + $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; + }]) + .directive('myCustomer', function() { + return { + restrict: 'E', + scope: { + customerInfo: '=info' + }, + templateUrl: 'my-customer-plus-vojta.html' + }; + }); + +angular.module('docsTimeDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.format = 'M/d/yy h:mm:ss a'; + }]) + .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { + + return { + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { + var format: any, + timeoutId: any; + + function updateTime() { + element.text(dateFilter(new Date(), format)); + } + + scope.$watch(attrs['myCurrentTime'], function (value: any) { + format = value; + updateTime(); + }); + + element.on('$destroy', function () { + $interval.cancel(timeoutId); + }); + + // start the UI update process; save the timeoutId for canceling + timeoutId = $interval(function () { + updateTime(); // update DOM + }, 1000); + } + }; + }]); + +angular.module('docsTransclusionDirective', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + templateUrl: 'my-dialog.html' + }; + }); + +angular.module('docsTransclusionExample', []) + .controller('Controller', ['$scope', function($scope: any) { + $scope.name = 'Tobias'; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + templateUrl: 'my-dialog.html', + link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) { + scope['name'] = 'Jeff'; + } + }; + }); + +angular.module('docsIsoFnBindExample', []) + .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { + $scope.name = 'Tobias'; + $scope.hideDialog = function () { + $scope.dialogIsHidden = true; + $timeout(function () { + $scope.dialogIsHidden = false; + }, 2000); + }; + }]) + .directive('myDialog', function() { + return { + restrict: 'E', + transclude: true, + scope: { + 'close': '&onClose' + }, + templateUrl: 'my-dialog-close.html' + }; + }); + +angular.module('dragModule', []) + .directive('myDraggable', ['$document', function($document: any) { + return function(scope: any, element: any, attr: any) { + var startX = 0, startY = 0, x = 0, y = 0; + + element.css({ + position: 'relative', + border: '1px solid red', + backgroundColor: 'lightgrey', + cursor: 'pointer' + }); + + element.on('mousedown', function(event: any) { + // Prevent default dragging of selected content + event.preventDefault(); + startX = event.pageX - x; + startY = event.pageY - y; + $document.on('mousemove', mousemove); + $document.on('mouseup', mouseup); + }); + + function mousemove(event: any) { + y = event.pageY - startY; + x = event.pageX - startX; + element.css({ + top: y + 'px', + left: x + 'px' + }); + } + + function mouseup() { + $document.off('mousemove', mousemove); + $document.off('mouseup', mouseup); + } + }; + }]); + +angular.module('docsTabsExample', []) + .directive('myTabs', function() { + return { + restrict: 'E', + transclude: true, + scope: {}, + controller: function($scope: ng.IScope) { + var panes: any = $scope['panes'] = []; + + $scope['select'] = function(pane: any) { + angular.forEach(panes, function(pane: any) { + pane.selected = false; + }); + pane.selected = true; + }; + + this.addPane = function(pane: any) { + if (panes.length === 0) { + $scope['select'](pane); + } + panes.push(pane); + }; + }, + templateUrl: 'my-tabs.html' + }; + }) + .directive('myPane', function() { + return { + require: '^myTabs', + restrict: 'E', + transclude: true, + scope: { + title: '@' + }, + link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { + tabsCtrl.addPane(scope); + }, + templateUrl: 'my-pane.html' + }; + }); diff --git a/angularjs/legacy/angular-1.2.d.ts b/angularjs/legacy/angular-1.2.d.ts new file mode 100644 index 000000000..a1a4cb15b --- /dev/null +++ b/angularjs/legacy/angular-1.2.d.ts @@ -0,0 +1,1182 @@ +// Type definitions for Angular JS 1.2+ +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var angular: ng.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject?: string[]; +} + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng { + + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new(...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + + // All service providers extend this interface + interface IServiceProvider { + $get: any; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + bootstrap(element: string, modules?: any[]): auto.IInjectorService; + bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; + bootstrap(element: Element, modules?: any[]): auto.IInjectorService; + bootstrap(element: Document, modules?: any[]): auto.IInjectorService; + copy(source: any, destination?: any): any; + element: IAugmentedJQueryStatic; + equals(value1: any, value2: any): boolean; + extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.IInjectorService; + isArray(value: any): boolean; + isDate(value: any): boolean; + isDefined(value: any): boolean; + isElement(value: any): boolean; + isFunction(value: any): boolean; + isNumber(value: any): boolean; + isObject(value: any): boolean; + isString(value: any): boolean; + isUndefined(value: any): boolean; + lowercase(str: string): string; + + /** + * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. + * + * @param name The name of the module to create or retrieve. + * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * @param configFn Optional configuration function for the module. + */ + module( + name: string, + requires?: string[], + configFn?: Function): IModule; + + noop(...args: any[]): void; + toJson(obj: any, pretty?: boolean): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codename: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + animation(name: string, animationFactory: Function): IModule; + animation(name: string, inlineAnnotatedFunction: any[]): IModule; + animation(object: Object): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param configFn Execute this function on module load. Useful for service configuration. + */ + config(configFn: Function): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. + */ + config(inlineAnnotatedFunction: any[]): IModule; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): IModule; + constant(object: Object): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, controllerConstructor: Function): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, inlineAnnotatedConstructor: any[]): IModule; + controller(object : Object): IModule; + directive(name: string, directiveFactory: IDirectiveFactory): IModule; + directive(name: string, inlineAnnotatedFunction: any[]): IModule; + directive(object: Object): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, $getFn: Function): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, inlineAnnotatedFunction: any[]): IModule; + factory(object: Object): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + filter(name: string, inlineAnnotatedFunction: any[]): IModule; + filter(object: Object): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; + provider(name: string, inlineAnnotatedConstructor: any[]): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; + provider(object: Object): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(initializationFunction: Function): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(inlineAnnotatedFunction: any[]): IModule; + service(name: string, serviceConstructor: Function): IModule; + service(name: string, inlineAnnotatedConstructor: any[]): IModule; + service(object: Object): IModule; + /** + * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. + + Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. + * + * @param name The name of the instance. + * @param value The value. + */ + value(name: string, value: any): IModule; + value(object: Object): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + // this is necessary to be able to access the scoped attributes. it's not very elegant + // because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + // this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + [name: string]: any; + + // Adds the CSS class value specified by the classVal parameter to the + // element. If animations are enabled then an animation will be triggered + // for the class addition. + $addClass(classVal: string): void; + + // Removes the CSS class value specified by the classVal parameter from the + // element. If animations are enabled then an animation will be triggered for + // the class removal. + $removeClass(classVal: string): void; + + // Set DOM element attribute value. + $set(key: string, value: any): void; + + // Observes an interpolated attribute. + // The observer function will be invoked once during the next $digest + // following compilation. The observer is then invoked whenever the + // interpolated value changes. + $observe(name: string, fn:(value?:any)=>any): Function; + + // A map of DOM element attribute names to the normalized name. This is needed + // to do reverse lookup from normalized name back to actual name. + $attr: Object; + } + + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ + interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + $error: any; + $addControl(control: ng.INgModelController): void; + $removeControl(control: ng.INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void; + $setDirty(): void; + $setPristine(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: boolean): void; + // Documentation states viewValue and modelValue to be a string but other + // types do work and it's common to use them. + $setViewValue(value: any): void; + $viewValue: any; + + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; + $error: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + interface IModelViewChangeListener { + (): void; + } + + /////////////////////////////////////////////////////////////////////////// + // Scope and RootScope + // see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and http://docs.angularjs.org/api/ng.$rootScope + /////////////////////////////////////////////////////////////////////////// + interface IRootScopeService { + $apply(): any; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + $emit(name: string, ...args: any[]): IAngularEvent; + + // Documentation says exp is optional, but actual implementaton counts on it + $eval(expression: string, args?: Object): any; + $eval(expression: (scope: IScope) => any, args?: Object): any; + + // Documentation says exp is optional, but actual implementaton counts on it + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean): IScope; + + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + + $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchGroup(watchExpressions: {(scope: IScope) : any}[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $parent: IScope; + + $root: IRootScopeService; + this: IRootScopeService; + + $id: string; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IScope extends IRootScopeService { + [index: string]: any; + } + + interface IAngularEvent { + targetScope: IScope; + currentScope: IScope; + name: string; + preventDefault: Function; + defaultPrevented: boolean; + + // Available only events that were $emit-ted + stopPropagation?: Function; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // FilterService + // see http://docs.angularjs.org/api/ng.$filter + // see http://docs.angularjs.org/api/ng.$filterProvider + /////////////////////////////////////////////////////////////////////////// + interface IFilterService { + (name: string): Function; + } + + interface IFilterProvider extends IServiceProvider { + register(name: string, filterFactory: Function): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + // see http://docs.angularjs.org/api/ng.$logProvider + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + debug: ILogCall; + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + interface ILogProvider { + debugEnabled(enabled: boolean): ILogProvider; + debugEnabled(): boolean; + } + + // We define this as separete interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + // see http://docs.angularjs.org/api/ng.$parseProvider + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface IParseProvider { + logPromiseWarnings(): boolean; + logPromiseWarnings(value: boolean): IParseProvider; + + unwrapPromises(): boolean; + unwrapPromises(value: boolean): IParseProvider; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // LocationService + // see http://docs.angularjs.org/api/ng.$location + // see http://docs.angularjs.org/api/ng.$locationProvider + // see http://docs.angularjs.org/guide/dev_guide.services.$location + /////////////////////////////////////////////////////////////////////////// + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + path(): string; + path(newPath: string): ILocationService; + port(): number; + protocol(): string; + replace(): ILocationService; + search(): any; + search(parametersMap: any): ILocationService; + search(parameter: string, parameterValue: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): boolean; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: boolean): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends IAugmentedJQuery {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ + interface IQService { + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array or hash of promises. + */ + all(promises: IPromise[]): IPromise; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array or hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any }>; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + defer(): IDeferred; + /** + * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ + reject(reason?: any): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(value: IPromise): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(value: T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(): IPromise; + } + + interface IPromise { + then(successCallback: (promiseValue: T) => IHttpPromise, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult, notifyCallback?: (state: any) => any): IPromise; + + + catch(onRejected: (reason: any) => IHttpPromise): IPromise; + catch(onRejected: (reason: any) => IPromise): IPromise; + catch(onRejected: (reason: any) => TResult): IPromise; + + finally(finallyCallback: ()=>any):IPromise; + } + + interface IDeferred { + resolve(value?: T): void; + reject(reason?: any): void; + notify(state?:any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CacheFactoryService + // see http://docs.angularjs.org/api/ng.$cacheFactory + /////////////////////////////////////////////////////////////////////////// + interface ICacheFactoryService { + // Lets not foce the optionsMap to have the capacity member. Even though + // it's the ONLY option considered by the implementation today, a consumer + // might find it useful to associate some other options to the cache object. + //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; + + // Methods bellow are not documented + info(): any; + get (cacheId: string): ICacheObject; + } + + interface ICacheObject { + info(): { + id: string; + size: number; + + // Not garanteed to have, since it's a non-mandatory option + //capacity: number; + }; + put(key: string, value?: any): void; + get (key: string): any; + remove(key: string): void; + removeAll(): void; + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; + } + + interface ICloneAttachFunction { + // Let's hint but not force cloneAttachFn's signature + (clonedElement?: JQuery, scope?: IScope): any; + } + + // This corresponds to the "publicLinkFn" returned by $compile. + interface ITemplateLinkingFunction { + (scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + // This corresponds to $transclude (and also the transclude function passed to link). + interface ITranscludeFunction { + // If the scope is provided, then the cloneAttachFn must be as well. + (scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery; + // If one argument is provided, then it's assumed to be the cloneAttachFn. + (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; + } + + /** + * HttpService + * see http://docs.angularjs.org/api/ng/service/$http + */ + interface IHttpService { + /** + * Object describing the request to be made and how it should be processed. + */ + (config: IRequestConfig): IHttpPromise; + + /** + * Shortcut method to perform GET request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + get(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform DELETE request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform HEAD request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + head(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform JSONP request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform POST request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PUT request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. + */ + defaults: IRequestConfig; + + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ + pendingRequests: any[]; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestShortcutConfig { + /** + * {Object.} + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + */ + params?: any; + + /** + * Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. + */ + headers?: any; + + /** + * Name of HTTP header to populate with the XSRF token. + */ + xsrfHeaderName?: string; + + /** + * Name of cookie containing the XSRF token. + */ + xsrfCookieName?: string; + + /** + * {boolean|Cache} + * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. + */ + cache?: any; + + /** + * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. + */ + withCredentials?: boolean; + + /** + * {string|Object} + * Data to be sent as the request message data. + */ + data?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. + */ + transformRequest?: any; + + /** + * {function(data, headersGetter)|Array.} + * Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. + */ + transformResponse?: any; + + /** + * {number|Promise} + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: any; + + /** + * See requestType. + */ + responseType?: string; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestConfig extends IRequestShortcutConfig { + /** + * HTTP method (e.g. 'GET', 'POST', etc) + */ + method: string; + /** + * Absolute or relative URL of the resource that is being requested. + */ + url: string; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: (headerName: string) => string, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: (headerName: string) => string; + config?: IRequestConfig; + statusText?: string; + } + + interface IHttpPromise extends IPromise { + success(callback: IHttpPromiseCallback): IHttpPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IRequestConfig; + interceptors: any[]; + responseInterceptors: any[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: boolean): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // SCEService + // see http://docs.angularjs.org/api/ng.$sce + /////////////////////////////////////////////////////////////////////////// + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEProvider + // see http://docs.angularjs.org/api/ng.$sceProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEProvider extends IServiceProvider { + enabled(value: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateService + // see http://docs.angularjs.org/api/ng.$sceDelegate + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateService { + getTrusted(type: string, mayBeTrusted: any): any; + trustAs(type: string, value: any): any; + valueOf(value: any): any; + } + + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateProvider + // see http://docs.angularjs.org/api/ng.$sceDelegateProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateProvider extends IServiceProvider { + resourceUrlBlacklist(blacklist: any[]): void; + resourceUrlWhitelist(whitelist: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // Directive + // see http://docs.angularjs.org/api/ng.$compileProvider#directive + // and http://docs.angularjs.org/guide/directive + /////////////////////////////////////////////////////////////////////////// + + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirectiveLinkFn { + ( + scope: IScope, + instanceElement: IAugmentedJQuery, + instanceAttributes: IAttributes, + controller: any, + transclude: ITranscludeFunction + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + transclude: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + link?: IDirectiveLinkFn; + name?: string; + priority?: number; + replace?: boolean; + require?: any; + restrict?: string; + scope?: any; + template?: any; + templateUrl?: any; + terminal?: boolean; + transclude?: any; + } + + /////////////////////////////////////////////////////////////////////////// + // angular.element + // when calling angular.element, angular returns a jQuery object, + // augmented with additional methods like e.g. scope. + // see: http://docs.angularjs.org/api/angular.element + /////////////////////////////////////////////////////////////////////////// + interface IAugmentedJQueryStatic extends JQueryStatic { + (selector: string, context?: any): IAugmentedJQuery; + (element: Element): IAugmentedJQuery; + (object: {}): IAugmentedJQuery; + (elementArray: Element[]): IAugmentedJQuery; + (object: JQuery): IAugmentedJQuery; + (func: Function): IAugmentedJQuery; + (array: any[]): IAugmentedJQuery; + (): IAugmentedJQuery; + } + + interface IAugmentedJQuery extends JQuery { + // TODO: events, how to define? + //$destroy + + find(selector: string): IAugmentedJQuery; + find(element: any): IAugmentedJQuery; + find(obj: JQuery): IAugmentedJQuery; + + controller(name: string): any; + injector(): any; + scope(): IScope; + isolateScope(): IScope; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; + } + + /////////////////////////////////////////////////////////////////////// + // AnimateService + // see http://docs.angularjs.org/api/ng.$animate + /////////////////////////////////////////////////////////////////////// + interface IAnimateService { + addClass(element: JQuery, className: string, done?: Function): void; + enter(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + leave(element: JQuery, done?: Function): void; + move(element: JQuery, parent: JQuery, after: JQuery, done?: Function): void; + removeClass(element: JQuery, className: string, done?: Function): void; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string): any; + has(name: string): boolean; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(inlineAnnotatedFunction: any[]): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): void; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, decorator: Function): void; + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, inlineAnnotatedFunction: any[]): void; + factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): ng.IServiceProvider; + provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; + service(name: string, constructor: Function): ng.IServiceProvider; + value(name: string, value: any): ng.IServiceProvider; + } + + } +} diff --git a/async/async-tests.ts b/async/async-tests.ts index 9b0c8e7ee..9a563276a 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -26,10 +26,11 @@ async.map(data, asyncProcess, function (err, results) { var openFiles = ['file1', 'file2']; var saveFile = function () { } -async.forEach(openFiles, saveFile, function (err) { }); +async.each(openFiles, saveFile, function (err) { }); +async.eachSeries(openFiles, saveFile, function (err) { }); var documents, requestApi; -async.forEachLimit(documents, 20, requestApi, function (err) { }); +async.eachLimit(documents, 20, requestApi, function (err) { }); async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); diff --git a/async/async.d.ts b/async/async.d.ts index d1d592629..994ed1799 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -34,9 +34,9 @@ interface AsyncQueue { interface Async { // Collections - forEach(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - forEachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - forEachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + each(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 6b40bb509..506fd7bb6 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -113,9 +113,12 @@ class EmployeeCollection extends Backbone.Collection { class Book extends Backbone.Model { title: string; author: string; + published: boolean; } class Library extends Backbone.Collection { + // This model definition is here only to test type compatibility of the model, but it + // is not necessary in working code as it is automatically inferred through generics. model: typeof Book; } @@ -123,31 +126,31 @@ class Books extends Backbone.Collection { } function test_collection() { - var books = new Library(); + var books = new Books(); - books.each(book => { - book.get("title"); - }); + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); - var titles = books.map(book => { - return book.get("title"); - }); + // Objects can be added to collection by casting to model type. + // Compiler will check if object properties are valid for the cast. + // This gives better type checking than declaring an `any` overload. + books.add({ title: "Title 2", author: "Mikey" }); - var publishedBooks = books.filter(book => { - return book.get("published") === true; - }); - - var alphabetical = books.sortBy((book: Book): number => { - return null; - }); - - var model: Book = new Book({title: "Test", author: "Mike"}); - books.add(model); - var model2: Book = model.collection.first(); - if (model !== model2) { + var model: Book = book1.collection.first(); + if (model !== book1) { throw new Error("Error"); } + books.each(book => + book.get("title")); + + var titles = books.map(book => + book.get("title")); + + var publishedBooks = books.filter(book => + book.get("published") === true); + + var alphabetical = books.sortBy((book: Book): number => null); } ////////// diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index db104f480..270b949aa 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -113,8 +113,23 @@ declare module Backbone { fetch(options?: ModelFetchOptions): JQueryXHR; - get(attributeName: string): any; - set(attributeName: string, value: any, options?: ModelSetOptions): Model; + /** + * For strongly-typed access to attributes, use the `get` method only privately in public getter properties. + * @example + * get name(): string { + * return super.get("name"); + * } + **/ + /*private*/ get(attributeName: string): any; + + /** + * For strongly-typed assignment of attributes, use the `set` method only privately in public setter properties. + * @example + * set name(value: string) { + * super.set("name", value); + * } + **/ + /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; change(): any; @@ -170,7 +185,12 @@ declare module Backbone { add(model: TModel, options?: AddOptions): Collection; add(models: TModel[], options?: AddOptions): Collection; at(index: number): TModel; + /** + * Get a model from a collection, specified by an id, a cid, or by passing in a model. + **/ + get(id: number): TModel; get(id: string): TModel; + get(id: Model): TModel; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; @@ -195,12 +215,10 @@ declare module Backbone { any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; chain(): any; - compact(): TModel[]; contains(value: any): boolean; countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; countBy(attribute: string): _.Dictionary; detect(iterator: (item: any) => boolean, context?: any): any; // ??? - difference(...model: TModel[]): TModel[]; drop(): TModel; drop(n: number): TModel[]; each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; @@ -209,7 +227,6 @@ declare module Backbone { find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; first(): TModel; first(n: number): TModel[]; - flatten(shallow?: boolean): TModel[]; foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; @@ -219,7 +236,6 @@ declare module Backbone { initial(): TModel; initial(n: number): TModel[]; inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - intersection(...model: TModel[]): TModel[]; isEmpty(object: any): boolean; invoke(methodName: string, arguments?: any[]): any; last(): TModel; @@ -228,7 +244,6 @@ declare module Backbone { map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - object(...values: any[]): any[]; reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; select(iterator: any, context?: any): any[]; size(): number; @@ -237,8 +252,6 @@ declare module Backbone { sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; sortBy(attribute: string, context?: any): TModel[]; sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; - range(stop: number, step?: number): any; - range(start: number, stop: number, step?: number): any; reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; rest(): TModel; @@ -246,10 +259,7 @@ declare module Backbone { tail(): TModel; tail(n: number): TModel[]; toArray(): any[]; - union(...model: TModel[]): TModel[]; - uniq(isSorted?: boolean, iterator?: (element: TModel, index: number) => boolean): TModel[]; without(...values: any[]): TModel[]; - zip(...model: TModel[]): TModel[]; } class Router extends Events { @@ -329,7 +339,6 @@ declare module Backbone { model: TModel; collection: Collection; //template: (json, options?) => string; - make(tagName: string, attrs?: any, opts?: any): View; setElement(element: HTMLElement, delegate?: boolean): View; setElement(element: JQuery, delegate?: boolean): View; id: string; @@ -355,11 +364,11 @@ declare module Backbone { function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; - var emulateJSONBackbone: boolean; + var emulateJSON: boolean; // Utility function noConflict(): typeof Backbone; - function setDomLibrary(jQueryNew: any): any; + var $: JQueryStatic; } declare module "backbone" { diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts new file mode 100644 index 000000000..6de9ee7cc --- /dev/null +++ b/big.js/big.js-tests.ts @@ -0,0 +1,233 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +/* + + Tests include code from http://mikemcl.github.io/big.js/ + + Minor changes have been made such as adding variable definitions where required. + +*/ + +function constructorTests() { + var x = new Big(9) // '9' + var y = new Big(x) // '9' + var d = Big(435.345) // 'new' is optional + var e = Big('435.345') // 'new' is optional + var a = new Big('5032485723458348569331745.33434346346912144534543') + var b = new Big('4.321e+4') // '43210' + var c = new Big('-735.0918e-430') // '-7.350918e-428' +} + +function staticPropertiesTests() { + Big.DP = 40; + Big.RM = 3; + Big.RM = BigJsLibrary.RoundingMode.RoundAwayFromZero; +} + +function absTests() { + var x = new Big(-0.8); + x.abs(); // '0.8' +} + +function cmpTests() { + var x = new Big(6); + var y = new Big(5); + x.cmp(y); // 1 + y.cmp(x.minus(1)); // 0 +} + +function divTests() { + var x = new Big(355); + var y = new Big(113); + x.div(y); // '3.14159292035398230088' + Big.DP = 2; + x.div(y); // '3.14' + x.div(5); // '71' +} + +function eqTests() { + 0 === 1e-324; // true + var x = new Big(0); + x.eq('1e-324'); // false + Big(-0).eq(x); // true ( -0 === 0 ) +} + +function gtTests() { + 0.1 > 0.3 - 0.2; // true + var x = new Big(0.1); + x.gt(Big(0.3).minus(0.2)); // false + Big(0).gt(x); // false +} + +function gteTests() { + 0.3 - 0.2 >= 0.1; // false + var x = new Big(0.3).minus(0.2); + x.gte(0.1); // true + Big(1).gte(x); // true +} + +function ltTests() { + 0.3 - 0.2 < 0.1; // true + var x = new Big(0.3).minus(0.2); + x.lt(0.1); // false + Big(0).lt(x); // true +} + +function lteTests() { + 0.1 <= 0.3 - 0.2; // false + var x = new Big(0.1); + x.lte(Big(0.3).minus(0.2)); // true + Big(-1).lte(x); // true +} + +function minusTests() { + 0.3 - 0.1; // 0.19999999999999998 + var x = new Big(0.3); + x.minus(0.1); // '0.2' +} + +function modTests() { + 1 % 0.9 // 0.09999999999999998 + var x = Big(1); + x.mod(0.9) // '0.1' +} + +function plusTests() { + 0.1 + 0.2 // 0.30000000000000004 + var x = new Big(0.1) + var y = x.plus(0.2) // '0.3' + Big(0.7).plus(x).plus(y) // '1' +} + +function powTests() { + Math.pow(0.7, 2) // 0.48999999999999994 + var x = new Big(0.7) + x.pow(2) // '0.49' + Big.DP = 20 + Big(3).pow(-2) // '0.11111111111111111111' + + new Big(123.456).pow(1000).toString().length // 5099 + new Big(2).pow(1e+6) // Time taken (Node.js): 9 minutes 34 secs. +} + +function roundTests() { + var x = 123.45 + Math.round(x) // 123 + var y = new Big(x) + y.round() // '123' + y.round(2) // '123.45' + y.round(10) // '123.45' + y.round(1, 0) // '123.4' + y.round(1, 1) // '123.5' + y.round(1, 2) // '123.4' + y.round(1, 3) // '123.5' + y // '123.45' +} + +function sqrtTests() { + var x = new Big(16) + x.sqrt() // '4' + var y = new Big(3) + y.sqrt() // '1.73205080756887729353' +} + +function timesTests() { + 0.6 * 3 // 1.7999999999999998 + var x = new Big(0.6) + var y = x.times(3) // '1.8' + Big('7e+500').times(y) // '1.26e+501' +} + +function toExponentialTests() { + var x = 45.6 + var y = new Big(x) + x.toExponential() // '4.56e+1' + y.toExponential() // '4.56e+1' + x.toExponential(0) // '5e+1' + y.toExponential(0) // '5e+1' + x.toExponential(1) // '4.6e+1' + y.toExponential(1) // '4.6e+1' + x.toExponential(3) // '4.560e+1' + y.toExponential(3) // '4.560e+1' +} + +function toFixedTests() { + var x = 45.6 + var y = new Big(x) + x.toFixed() // '46' + y.toFixed() // '45.6' + y.toFixed(0) // '46' + x.toFixed(3) // '45.600' + y.toFixed(3) // '45.600' +} + +function toPrecisionTests() { + var x = 45.6 + var y = new Big(x) + x.toPrecision() // '45.6' + y.toPrecision() // '45.6' + x.toPrecision(1) // '5e+1' + y.toPrecision(1) // '5e+1' + x.toPrecision(5) // '45.600' + y.toPrecision(5) // '45.600' +} + +function toStringTests() { + var x = new Big('9.99e+20') + x.toString() // '999000000000000000000' + var y = new Big('1E21') + x.toString() // '1e+21' +} + +function valueOfTests() { + var x = new Big('177.7e+457') + x.valueOf() // '1.777e+459' +} + +function toJSONTests() { + var x = new Big('177.7e+457') + var y = new Big(235.4325) + var z = new Big('0.0098074') + var str = JSON.stringify([x, y, z]) + + var a = new Big('123').toJSON(); + + JSON.parse(str, function (k, v) { return k === '' ? v : new Big(v) }) // Returns an array of three Big numbers. +} + +function propertiesTest1() { + var x = new Big(0.123) // '0.123' + x.toExponential() // '1.23e-1' + x.c // '1,2,3' + x.e // -1 + x.s // 1 + + var y = new Number(-123.4567000e+2) // '-12345.67' + y.toExponential() // '-1.234567e+4' + var z = new Big('-123.4567000e+2') // '-12345.67' + z.toExponential() // '-1.234567e+4' + z.c // '1,2,3,4,5,6,7' + z.e // 4 + z.s // -1 +} + +function propertiesTest2() { + var x = new Big('1234.000') // '1234' + x.toExponential() // '1.234e+3' + x.c // '1,2,3,4' + x.e // 3 + + x.e = -5 + x // '0.00001234' +} + +function propertiesTest3() { + var y = new Big(-0) // '0' + y.c // '0' [0].toString() + y.e // 0 + y.s // -1 +} \ No newline at end of file diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts new file mode 100644 index 000000000..4f6278a80 --- /dev/null +++ b/big.js/big.js.d.ts @@ -0,0 +1,200 @@ +// Type definitions for big.js +// Project: https://github.com/MikeMcl/big.js/ +// Definitions by: Steve Ognibene +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module BigJsLibrary { + + export enum RoundingMode { + RoundTowardsZero = 0, + RoundTowardsNearestAwayFromZero = 1, + RoundTowardsNearestTowardsEven = 2, + RoundAwayFromZero = 3 + } + + interface BigJS extends BigJS_Constructors { + /** The maximum number of decimal places of the results of operations involving division. + It is relevant only to the div and sqrt methods, and the pow method when the exponent is negative. + @default 40 */ + DP: number; + + /** The rounding mode used in the above operations and by round, toExponential, toFixed and toPrecision. + Default is RoundTowardsNearestAwayFromZero + @default 1 */ + RM: RoundingMode; + } + + interface BigJS_Constructors { + /** A decimal value. */ + new (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + new (value: string): BigJS; + /** A decimal value. */ + new (value: BigJS): BigJS; + /** A decimal value. */ + (value: number): BigJS; + /** A decimal value. + String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. + String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ + (value: string): BigJS; + /** A decimal value. */ + (value: BigJS): BigJS; + } + + /** BigJS instance methods */ + interface BigJS extends BigJS_Constructors { + /** Returns a Big number whose value is the absolute value, i.e. the magnitude, of this Big number. */ + abs(): BigJS; + + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: number): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: string): number; + /** Compare + @returns {Number} + 1 = If the value of this Big number is greater than the value of n + -1 = If the value of this Big number is less than the value of n + 0 = If this Big number and n have the same value */ + cmp(n: BigJS): number; + + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number divided by n. */ + div(n: BigJS): BigJS; + + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: number): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: string): boolean; + /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ + eq(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: number): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: string): boolean; + /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ + gt(n: BigJS): boolean; + + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: number): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: string): boolean; + /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ + gte(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: number): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: string): boolean; + /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ + lt(n: BigJS): boolean; + + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: number): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: string): boolean; + /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ + lte(n: BigJS): boolean; + + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number minus n. */ + minus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number plus n. */ + plus(n: BigJS): BigJS; + + /** Returns a Big number whose value is the value of this Big number raised to the power exp. + If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM. + @param exp integer, -1e+6 to 1e+6 inclusive */ + pow(exp: number): BigJS; + + /** Returns a Big number whose value is the value of this Big number rounded to a whole number. */ + round(): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. */ + round(dp: number): BigJS; + /** Returns a Big number whose value is the value of this Big number rounded using rounding mode rm to a maximum of dp decimal places. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted or is null or undefined, the return value is n rounded to a whole number. + @param rm Rounding mode. If rm is omitted or is null or undefined, the current Big.RM setting is used. */ + round(dp: number, rm: RoundingMode): BigJS; + + /** Returns a Big number whose value is the square root of this Big number. */ + sqrt(): BigJS; + + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: number): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: string): BigJS; + /** Returns a Big number whose value is the value of this Big number times n. */ + times(n: BigJS): BigJS; + + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */ + toExponential(): string; + /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly. */ + toExponential(dp: number): string; + + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. */ + toFixed(): string; + /** Returns a string representing the value of this Big number in normal notation to a fixed number of decimal places dp. + @param dp Number of decimal places (0 to 1e+6 inclusive). If dp is omitted, or is null or undefined, then the return value is simply the value in normal notation. This is also unlike Number.prototype.toFixed, which returns the value to zero decimal places. */ + toFixed(dp: number): string; + + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. */ + toPrecision(): string; + /** Returns a string representing the value of this Big number to the specified number of significant digits sd. + @param sd significant digits. If sd is omitted, or is null or undefined, then the return value is the same as .toString(). */ + toPrecision(sd: number /** number of significant digits (0 to 1e+6 inclusive) */): string; + + /** Returns a string representing the value of this Big number. */ + toString(): string; + + /** As toString. */ + valueOf(): string; + + /** As toString. */ + toJSON(): string; + + /** coefficient (significand) */ + c: number[]; + + /** exponent (Integer, -1e+6 to 1e+6 inclusive) */ + e: number; + + /** sign (-1 or 1) */ + s: number; + } +} + +declare var Big: BigJsLibrary.BigJS; \ No newline at end of file diff --git a/bigint/bigint-tests.ts b/bigint/bigint-tests.ts new file mode 100644 index 000000000..8ccf2ba4b --- /dev/null +++ b/bigint/bigint-tests.ts @@ -0,0 +1,81 @@ +/// + +var bi: BigInt.BigInt; +var num: number; +var str: string; +var b: boolean; + +BigInt.setRandom(() => { return 0; }); + +bi = BigInt.add(bi, bi); +bi = BigInt.addInt(bi, num); +str = BigInt.bigInt2str(bi, num); +str = BigInt.bigInt2str(bi, str); +num = BigInt.bitSize(bi); +bi = BigInt.dup(bi); +b = BigInt.equals(bi, bi); +b = BigInt.equalsInt(bi, num); +bi = BigInt.expand(bi, num); +var nums: number[] = BigInt.findPrimes(num); +bi = BigInt.GCD(bi, bi); +b = BigInt.greater(bi, bi); +b = BigInt.greaterShift(bi, bi, num); +bi = BigInt.int2bigInt(0); +bi = BigInt.int2bigInt(0, 0); +bi = BigInt.int2bigInt(0, 0, 0); +bi = BigInt.inverseMod(bi, bi); +bi = BigInt.inverseModInt(num, num); +b = BigInt.isZero(bi); +b = BigInt.millerRabin(bi, bi); +b = BigInt.millerRabinInt(num, num); +bi = BigInt.mod(bi, bi); +num = BigInt.modInt(bi, num); +bi = BigInt.mult(bi, bi); +bi = BigInt.multMod(bi, bi, bi); +b = BigInt.negative(bi); +bi = BigInt.powMod(bi, bi, bi); +bi = BigInt.randBigInt(num, num); +bi = BigInt.randTruePrime(num); +bi = BigInt.randProbPrime(num); +bi = BigInt.str2bigInt(str, num); +bi = BigInt.str2bigInt(str, num, 0); +bi = BigInt.str2bigInt(str, num, 0, 0); +bi = BigInt.str2bigInt(str, str); +bi = BigInt.str2bigInt(str, str, 0); +bi = BigInt.str2bigInt(str, str, 0, 0); +bi = BigInt.sub(bi, bi); +bi = BigInt.trim(bi, num); + +BigInt.addInt_(bi, num); +BigInt.add_(bi, bi); +BigInt.copy_(bi, bi); +num = BigInt.copyInt_(bi, num); +BigInt.GCD_(bi, bi); +b = BigInt.inverseMod_(bi, bi); +BigInt.mod_(bi, bi); +BigInt.mult_(bi, bi); +BigInt.multMod_(bi, bi, bi); +BigInt.powMod_(bi, bi, bi); +BigInt.randBigInt_(bi, num, num); +BigInt.randTruePrime_(bi, num); +BigInt.sub_(bi, bi); +BigInt.addShift_(bi, bi, num); +BigInt.carry_(bi); +BigInt.divide_(bi, bi, bi, bi); +num = BigInt.divInt_(bi, num); +BigInt.eGCD_(bi, bi, bi, bi, bi); +BigInt.halve_(bi); +BigInt.leftShift_(bi, num); +BigInt.linComb_(bi, bi, num, num); +BigInt.linCombShift_(bi, bi, num, num); +BigInt.mont_(bi, bi, bi, num); +BigInt.multInt_(bi, num); +BigInt.rightShift_(bi, num); +BigInt.squareMod_(bi, bi); +BigInt.subShift_(bi, bi, num); + +function someRandomRealCode() { + bi = BigInt.int2bigInt(22, 5); + bi = BigInt.str2bigInt("FFFFFFFFFFFFFFFFC90FDAA2", 16); + str = BigInt.bigInt2str(bi, 16); +} diff --git a/bigint/bigint.d.ts b/bigint/bigint.d.ts new file mode 100644 index 000000000..b70f20fa4 --- /dev/null +++ b/bigint/bigint.d.ts @@ -0,0 +1,371 @@ +// Type definitions for BigInt v5.5.1 +// Project: https://github.com/Evgenus/BigInt +// Definitions by: Eugene Chernyshov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module BigInt { + export interface BigInt extends Array { + } + + export interface IRandom { + (): number; + } + + export function setRandom(random: IRandom): void; + + /** + * bigInt add(x,y) + * return (x+y) for bigInts x and y. + */ + 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. + */ + 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; + + /** + * int bitSize(x) + * return how many bits long the bigInt x is, not counting leading zeros + */ + export function bitSize(x: BigInt): number; + + /** + * bigInt dup(x) + * return a copy of bigInt x + */ + export function dup(x: BigInt): BigInt; + + /** + * boolean equals(x,y) + * is the bigInt x equal to the bigint y? + */ + export function equals(x: BigInt, y: BigInt): boolean; + + /** + * boolean equalsInt(x,y) + * is bigint x equal to integer y? + */ + 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 + */ + export function expand(value: BigInt, n: number): BigInt; + + /** + * Array findPrimes(n) + * return array of all primes less than integer n + */ + 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). + */ + export function GCD(x: BigInt, y: BigInt): BigInt; + + /** + * boolean greater(x,y) + * is x>y? (x and y are nonnegative bigInts) + */ + export function greater(x: BigInt, y: BigInt): boolean; + + /** + * boolean greaterShift(x,y,shift) + * is (x <<(shift*bpe)) > y? + */ + 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 + */ + 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 + */ + 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 + */ + export function inverseModInt(x: number, n: number): BigInt; + + /** + * boolean isZero(x) + * is the bigInt x equal to zero? + */ + 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. + */ + export function randBigInt(n: number, s: number): BigInt; + + /** + * bigInt randTruePrime(k) + * return a new, random, k-bit, true prime bigInt using Maurer's algorithm. + */ + 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). + */ + 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; + + /** + * bigInt sub(x,y) + * return (x-y) for bigInts x and y. Negative answers will be 2s complement + */ + export function sub(x: BigInt, y: BigInt): BigInt; + + /** + * bigInt trim(x,k) + * return a copy of x with exactly k leading zero elements + */ + 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 + */ + export function addInt_(x: BigInt, n: number): void; + + /** + * void add_(x,y) + * do x=x+y for bigInts x and y + */ + export function add_(x: BigInt, y: BigInt): void; + + /** + * void copy_(x,y) + * do x=y on bigInts x and y + */ + export function copy_(x: BigInt, y: BigInt): void; + + /** + * void copyInt_(x,n) + * do x=n on bigInt x and integer n + */ + export function copyInt_(x: BigInt, n: number): number; + + /** + * void GCD_(x,y) + * set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array). + */ + 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 + */ + 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). + */ + export function mod_(x: BigInt, n: BigInt): void; + + /** + * void mult_(x,y) + * do x=x*y for bigInts x and y. + */ + export function mult_(x: BigInt, y: BigInt): void; + + /** + * void multMod_(x,y,n) + * do x=x*y mod n for bigInts x,y,n. + */ + 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. + */ + 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. + */ + 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. + */ + 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. + */ + export function sub_(x: BigInt, y: BigInt): void; + + /** + * void addShift_(x,y,ys) + * do x=x+(y<<(ys*bpe)) + */ + 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. + */ + export function carry_(x: BigInt): void; + + /** + * void divide_(x,y,q,r) + * divide x by y giving quotient q and remainder r + */ + 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). + */ + 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 + */ + 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). + */ + export function halve_(x: BigInt): void; + + /** + * void leftShift_(x,n) + * left shift bigInt x by n bits. n, VILIC VANE , Jonathan Häberle +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "body-parser" { + import express = require('express'); + + /** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ + + function bodyParser(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + + module bodyParser { + export function json(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'json') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + }): express.RequestHandler; + + export function raw(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + }): express.RequestHandler; + + export function text(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * the default charset to parse as, if not specified in content-type. (default: 'utf-8') + */ + defaultCharset?: string; + }): express.RequestHandler; + + export function urlencoded(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + } + + export = bodyParser; +} \ No newline at end of file diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts index 5326abaeb..02ac29bf2 100644 --- a/browserify/browserify.d.ts +++ b/browserify/browserify.d.ts @@ -22,6 +22,8 @@ interface BrowserifyObject extends NodeJS.EventEmitter { ignore(file: string): BrowserifyObject; transform(tr: string): BrowserifyObject; transform(tr: Function): BrowserifyObject; + plugin(plugin: string, opts?: any): BrowserifyObject; + plugin(plugin: Function, opts?: any): BrowserifyObject; } declare module "browserify" { @@ -33,4 +35,4 @@ declare module "browserify" { }): BrowserifyObject; export = browserify; -} \ No newline at end of file +} diff --git a/bucks/bucks-tests.ts b/bucks/bucks-tests.ts new file mode 100644 index 000000000..5ebbd882c --- /dev/null +++ b/bucks/bucks-tests.ts @@ -0,0 +1,222 @@ +/// + +function add_and_end() { + // + // new Bucks object + // + var b = new Bucks(); + + // + // Add and add several tasks. + // + b.add(function f1(err, res) { + + return 'a'; + + }).add(function f2(err, res, next) { + + // res => 'a' + return next(null, 3); + + }).add(function f3(err, res, next) { + + // res => 3 + return next(new Error('error after 3')); + + }).add(function f4(err, res, next) { + + // err => 'error after 3' + return next(null, "recover 4"); + + }).add(function f5(err, res) { + + // res => 'recover 4' + throw new Error('error in f5'); + + }).add(function f6(err, res) { + + // err => 'error in f5' + throw err; + + }).add(function f7(err, res) { + + // err => 'error in f5' + // ignore and return + return "recover 7"; + + }).add(function f8(err, res, next) { + + // res => 'recover 7'; + throw new Error('error in f8'); + + }).add(function f9(err, res, next) { + + // err => 'Error in f8' + // ignore error + return next(null, 'result of 9'); + + }).end(function last(err, results) { + + // all of results + // are obtained in #end + + // err => null + + // results => [ + // 'a', + // null, + // null, + // 'recover 4', + // null, + // null, + // 'recover 7', + // null, + // 'result of 9' + // ]; + }); +} + +function then() { + var b = new Bucks(); + b.then(function start() { + return 'start'; + }).then(function second(res, next) { + // res => 'start' + return next(null, 'second') + }).end(); +} + +function delay() { + var b = new Bucks(); + b.add(function (){ /** program */ }) + .delay(1 * 1000) // 1ms + .add(function() { /** program */}) + .end(); +} + +function error() { + var b = new Bucks(); + b.then(function start() { + throw new Error('error in start'); + return 'start'; + }).error(function onError(e, next) { + // e => 'error in start' + return next(); + }).end(); +} + +function final_errorback_in_end() { + // + // last error back + // + var b = new Bucks(); + b.empty( + // add empty task (#end with no task cause error) + ).end(function last(err, res) { + // error in last callback + throw new Error('error in end'); + }, function finalErrorback(err) { + // catch uncaught error in last callback + // err => 'error in end' + }); +} + +function uncaught_error() { + try { + var b = new Bucks(); + b.then(function () { + throw new Error('error'); + }).end(); + } catch(e) { + // e => 'error' + } +} + +function waterfall() { + var t1: Bucks.Task = function t1(err, res) { + return 't1'; + }; + var t2: Bucks.Task = function t2(err, res) { + return 't2'; + }; + + new Bucks().waterfall([t1, t2]).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); + + // same as + new Bucks().add(t1).add(t2).end(function finish(err, ress) { + // ress => ['t1', 't2'] + }); +} + +function parallel() { + var b = new Bucks(); + + b.parallel([ + function task1(err, res) { + return "task1"; + }, + function task2(err, res, next) { + return next(null, "task2"); + }, + function task3(err, res, next) { + return next(new Error('passed error in task3')); + }, + function task4(err, res, next) { + throw new Error('thrown error in task4'); + } + ]).add(function getResults(err, res, next) { + // res => { + // err: [ + // null, + // null, + // [Error: passed error in task3], + // [Error: thrown error in task4] + // ], + // res: [ + // 'task1', + // 'task2', + // null, + // null + // ] + // } + next(); + }).end(); +} + +function onError() { + var onError = function (e: Error, bucks: Bucks.Bucks) { + console.log("Custom onError"); + }; + + // Bucks.onError!! + Bucks.onError(onError); + var b0 = new Bucks(); + b0 + .add(function(err, next) { + throw new Error('b0'); + }) + .end() + ; +} + +function dispose() { + var b0 = new Bucks(); + + b0.dispose = function dispose () { + // delete b0.dummy; + } + + b0 + .add(function(err, next) { + // b0.dummy = "dummy"; + next(); + }) + .end(null, null) + ; +} + +function debug() { + Bucks.DEBUG = true; +} diff --git a/bucks/bucks.d.ts b/bucks/bucks.d.ts new file mode 100644 index 000000000..cac3c7121 --- /dev/null +++ b/bucks/bucks.d.ts @@ -0,0 +1,113 @@ +// Type definitions for bucks.js 0.8.3 +// Project: https://github.com/CyberAgent/bucks.js +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Bucks { + + interface BucksStatic { + + /** + * bucks.js version. + */ + VERSION: string; + + /** + * If set `true`, uncaught errors are logged. + */ + DEBUG: boolean; + + /** + * Running bucks objects. + */ + running: Bucks[]; + + /** + * Not yet called `end` bucks object. + */ + living: Bucks[]; + + /** + * Create bucks object. + */ + new(): Bucks; + + /** + * Catch all errors. + * @param onError Function called after catching error + */ + onError(onError: (err:Error, bucks:Bucks)=>any): void; + } + + interface Bucks { + + /** + * Add a task. + * @param task Function added async chain + */ + add(task: TaskWithNext): Bucks; + + /** + * Add a task called only in case of success. + * @param onSuccess Function called only in case of success + */ + then(onSuccess: (res:any, next?:Task)=>any): Bucks; + + /** + * Add a empty task. + */ + empty(): Bucks; + + /** + * Add a task called only in case of error. + * @param onError Function called only in case of error + */ + error(onError: (err:Error, next?:Task)=>any): Bucks; + + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions called in asynchronous way and join their results + */ + parallel(tasks: TaskWithNext[]): Bucks; + + /** + * Add tasks in asynchronous way and join their results. + * @param tasks Functions added async chain + */ + waterfall(tasks: TaskWithNext[]): Bucks; + + /** + * Add delay execution. + * @param ms number millisecond for delaying + */ + delay(ms: number): Bucks; + + /** + * Called when destroy async chain. + */ + dispose(): void; + + /** + * Destroy this object and call last callback function. + * @param err If specify err and no callback, throw to execute failure callback + */ + destroy(err?: Error): Bucks; + + /** + * Complete creating async chain and start executing. + * @param callback Last callback function + * @param errback Handler for occurring error in last callback function + */ + end(callback?: Task, errback?: (err:Error)=>any): void; + } + + interface TaskWithNext { + (err?: Error, res?: any, next?: Task): any; + } + + interface Task { + (err?: Error, res?: any): any; + } +} + +declare var Bucks: Bucks.BucksStatic; diff --git a/chai-datetime/chai-datetime-tests.ts b/chai-datetime/chai-datetime-tests.ts index 0b7ff729f..8f8238b4e 100644 --- a/chai-datetime/chai-datetime-tests.ts +++ b/chai-datetime/chai-datetime-tests.ts @@ -1,8 +1,8 @@ /// -/// /// var expect = chai.expect; +var assert = chai.assert; function test_equalTime(){ var date: Date = new Date(2014, 1, 1); @@ -44,4 +44,4 @@ function test_afterDate(){ expect(date).to.afterDate(date); date.should.afterDate(date); assert.afterDate(date, date); -} \ No newline at end of file +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts b/chai-fuzzy/chai-fuzzy.d.ts similarity index 91% rename from chai-fuzzy/chai-fuzzy-assert.d.ts rename to chai-fuzzy/chai-fuzzy.d.ts index f75f99d55..0cbb1741b 100644 --- a/chai-fuzzy/chai-fuzzy-assert.d.ts +++ b/chai-fuzzy/chai-fuzzy.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module chai { interface Assert { @@ -14,4 +14,4 @@ declare module chai { jsonOf(act:any, exp:any, msg?:string); notJsonOf(act:any, exp:any, msg?:string); } -} \ No newline at end of file +} diff --git a/chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams b/chai-fuzzy/chai-fuzzy.d.ts.tscparams similarity index 100% rename from chai-fuzzy/chai-fuzzy-assert.d.ts.tscparams rename to chai-fuzzy/chai-fuzzy.d.ts.tscparams diff --git a/chai/chai-assert-tests.ts b/chai/chai-assert-tests.ts deleted file mode 100644 index 4dc430f0c..000000000 --- a/chai/chai-assert-tests.ts +++ /dev/null @@ -1,655 +0,0 @@ -/* - ---------- - test extracted from original test suite - chai original licence follows ---------- - -## License - -(The MIT License) - -Copyright (c) 2011-2013 Jake Luer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -/// - -//stubs - -//tdd -declare function suite(description: string, action: Function):void; -declare function test(description: string, action: Function):void; -declare function err(action: any, msg?: string):void; -interface FieldObj { - field: any; -} -class Foo { - constructor() { - - } -} - -class CrashyObject { - inspect (): void { - throw new Error("Arg's inspect() called even though the test passed"); - } -} - -suite('assert', function () { - - test('assert', function () { - var foo = 'bar'; - assert(foo == 'bar', "expected foo to equal `bar`"); - - err(function () { - assert(foo == 'baz', "expected foo to equal `bar`"); - }, "expected foo to equal `bar`"); - }); - - test('isTrue', function () { - assert.isTrue(true); - - err(function () { - assert.isTrue(false); - }, "expected false to be true"); - - err(function () { - assert.isTrue(1); - }, "expected 1 to be true"); - - err(function () { - assert.isTrue('test'); - }, "expected 'test' to be true"); - }); - - test('ok', function () { - assert.ok(true); - assert.ok(1); - assert.ok('test'); - - err(function () { - assert.ok(false); - }, "expected false to be truthy"); - - err(function () { - assert.ok(0); - }, "expected 0 to be truthy"); - - err(function () { - assert.ok(''); - }, "expected '' to be truthy"); - }); - - test('isFalse', function () { - assert.isFalse(false); - - err(function () { - assert.isFalse(true); - }, "expected true to be false"); - - err(function () { - assert.isFalse(0); - }, "expected 0 to be false"); - }); - - test('equal', function () { - var foo: any; - assert.equal(foo, undefined); - }); - - test('typeof / notTypeOf', function () { - assert.typeOf('test', 'string'); - assert.typeOf(true, 'boolean'); - assert.typeOf(5, 'number'); - - err(function () { - assert.typeOf(5, 'string'); - }, "expected 5 to be a string"); - - }); - - test('notTypeOf', function () { - assert.notTypeOf('test', 'number'); - - err(function () { - assert.notTypeOf(5, 'number'); - }, "expected 5 not to be a number"); - }); - - test('instanceOf', function () { - assert.instanceOf(new Foo(), Foo); - - err(function () { - assert.instanceOf(5, Foo); - }, "expected 5 to be an instance of Foo"); - assert.instanceOf(new CrashyObject(), CrashyObject); - }); - - test('notInstanceOf', function () { - assert.notInstanceOf(new Foo(), String); - - err(function () { - assert.notInstanceOf(new Foo(), Foo); - }, "expected {} to not be an instance of Foo"); - }); - - test('isObject', function () { - assert.isObject({}); - assert.isObject(new Foo()); - - err(function () { - assert.isObject(true); - }, "expected true to be an object"); - - err(function () { - assert.isObject(Foo); - }, "expected [Function: Foo] to be an object"); - - err(function () { - assert.isObject('foo'); - }, "expected 'foo' to be an object"); - }); - - test('isNotObject', function () { - assert.isNotObject(5); - - err(function () { - assert.isNotObject({}); - }, "expected {} not to be an object"); - }); - - test('notEqual', function () { - assert.notEqual(3, 4); - - err(function () { - assert.notEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('strictEqual', function () { - assert.strictEqual('foo', 'foo'); - - err(function () { - assert.strictEqual('5', 5); - }, "expected \'5\' to equal 5"); - }); - - test('notStrictEqual', function () { - assert.notStrictEqual(5, '5'); - - err(function () { - assert.notStrictEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('deepEqual', function () { - assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); - - err(function () { - assert.deepEqual({tea: 'chai'}, {tea: 'black'}); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - - var obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); - - assert.deepEqual(obja, objb); - - var obj1 = Object.create({tea: 'chai'}) - , obj2 = Object.create({tea: 'black'}); - - err(function () { - assert.deepEqual(obj1, obj2); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - }); - - test('deepEqual (ordering)', function () { - var a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; - assert.deepEqual(a, b); - }); - - test('deepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = {}; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.deepEqual(circularObject, secondCircularObject); - - err(function () { - secondCircularObject.field2 = secondCircularObject; - assert.deepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); - }); - - test('notDeepEqual', function () { - assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); - err(function () { - assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); - }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); - }); - - test('notDeepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = { tea: 'jasmine' }; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.notDeepEqual(circularObject, secondCircularObject); - - err(function () { - delete secondCircularObject.tea; - assert.notDeepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); - }); - - test('isNull', function () { - assert.isNull(null); - - err(function () { - assert.isNull(undefined); - }, "expected undefined to equal null"); - }); - - test('isNotNull', function () { - assert.isNotNull(undefined); - - err(function () { - assert.isNotNull(null); - }, "expected null to not equal null"); - }); - - test('isUndefined', function () { - assert.isUndefined(undefined); - - err(function () { - assert.isUndefined(null); - }, "expected null to equal undefined"); - }); - - test('isDefined', function () { - assert.isDefined(null); - - err(function () { - assert.isDefined(undefined); - }, "expected undefined to not equal undefined"); - }); - - test('isFunction', function () { - var func = function () { - }; - assert.isFunction(func); - - err(function () { - assert.isFunction({}); - }, "expected {} to be a function"); - }); - - test('isNotFunction', function () { - assert.isNotFunction(5); - - err(function () { - assert.isNotFunction(function () { - }); - }, "expected [Function] not to be a function"); - }); - - test('isArray', function () { - assert.isArray([]); - assert.isArray(new Array()); - - err(function () { - assert.isArray({}); - }, "expected {} to be an array"); - }); - - test('isNotArray', function () { - assert.isNotArray(3); - - err(function () { - assert.isNotArray([]); - }, "expected [] not to be an array"); - - err(function () { - assert.isNotArray(new Array()); - }, "expected [] not to be an array"); - }); - - test('isString', function () { - assert.isString('Foo'); - assert.isString(new String('foo')); - - err(function () { - assert.isString(1); - }, "expected 1 to be a string"); - }); - - test('isNotString', function () { - assert.isNotString(3); - assert.isNotString([ 'hello' ]); - - err(function () { - assert.isNotString('hello'); - }, "expected 'hello' not to be a string"); - }); - - test('isNumber', function () { - assert.isNumber(1); - assert.isNumber(Number('3')); - - err(function () { - assert.isNumber('1'); - }, "expected \'1\' to be a number"); - }); - - test('isNotNumber', function () { - assert.isNotNumber('hello'); - assert.isNotNumber([ 5 ]); - - err(function () { - assert.isNotNumber(4); - }, "expected 4 not to be a number"); - }); - - test('isBoolean', function () { - assert.isBoolean(true); - assert.isBoolean(false); - - err(function () { - assert.isBoolean('1'); - }, "expected \'1\' to be a boolean"); - }); - - test('isNotBoolean', function () { - assert.isNotBoolean('true'); - - err(function () { - assert.isNotBoolean(true); - }, "expected true not to be a boolean"); - - err(function () { - assert.isNotBoolean(false); - }, "expected false not to be a boolean"); - }); - - test('include', function () { - assert.include('foobar', 'bar'); - assert.include([ 1, 2, 3], 3); - - err(function () { - assert.include('foobar', 'baz'); - }, "expected \'foobar\' to contain \'baz\'"); - - err(function () { - assert.include(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('notInclude', function () { - assert.notInclude('foobar', 'baz'); - assert.notInclude([ 1, 2, 3 ], 4); - - err(function () { - assert.notInclude('foobar', 'bar'); - }, "expected \'foobar\' to not contain \'bar\'"); - - err(function () { - assert.notInclude(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('lengthOf', function () { - assert.lengthOf([1, 2, 3], 3); - assert.lengthOf('foobar', 6); - - err(function () { - assert.lengthOf('foobar', 5); - }, "expected 'foobar' to have a length of 5 but got 6"); - - err(function () { - assert.lengthOf(1, 5); - }, "expected 1 to have a property \'length\'"); - }); - - test('match', function () { - assert.match('foobar', /^foo/); - assert.notMatch('foobar', /^bar/); - - err(function () { - assert.match('foobar', /^bar/i); - }, "expected 'foobar' to match /^bar/i"); - - err(function () { - assert.notMatch('foobar', /^foo/i); - }, "expected 'foobar' not to match /^foo/i"); - }); - - test('property', function () { - var obj = { foo: { bar: 'baz' } }; - var simpleObj = { foo: 'bar' }; - assert.property(obj, 'foo'); - assert.deepProperty(obj, 'foo.bar'); - assert.notProperty(obj, 'baz'); - assert.notProperty(obj, 'foo.bar'); - assert.notDeepProperty(obj, 'foo.baz'); - assert.deepPropertyVal(obj, 'foo.bar', 'baz'); - assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); - - err(function () { - assert.property(obj, 'baz'); - }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); - - err(function () { - assert.deepProperty(obj, 'foo.baz'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); - - err(function () { - assert.notProperty(obj, 'foo'); - }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); - - err(function () { - assert.notDeepProperty(obj, 'foo.bar'); - }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); - - err(function () { - assert.propertyVal(simpleObj, 'foo', 'ball'); - }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); - - err(function () { - assert.deepPropertyVal(obj, 'foo.bar', 'ball'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); - - err(function () { - assert.propertyNotVal(simpleObj, 'foo', 'bar'); - }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); - - err(function () { - assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); - }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); - }); - - test('throws', function () { - assert.throws(function () { - throw new Error('foo'); - }); - assert.throws(function () { - throw new Error('bar'); - }, 'bar'); - assert.throws(function () { - throw new Error('bar'); - }, /bar/); - assert.throws(function () { - throw new Error('bar'); - }, Error); - assert.throws(function () { - throw new Error('bar'); - }, Error, 'bar'); - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, Error, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError, 'bar'); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - }); - }, "expected [Function] to throw an error"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got ''"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, /bar/); - }, "expected [Function] to throw error matching /bar/ but got ''"); - }); - - test('doesNotThrow', function () { - assert.doesNotThrow(function () { - }); - assert.doesNotThrow(function () { - }, 'foo'); - - err(function () { - assert.doesNotThrow(function () { - throw new Error('foo'); - }); - }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); - }); - - test('ifError', function () { - assert.ifError(false); - assert.ifError(null); - assert.ifError(undefined); - - err(function () { - assert.ifError('foo'); - }, "expected \'foo\' to be falsy"); - }); - - test('operator', function () { - assert.operator(1, '<', 2); - assert.operator(2, '>', 1); - assert.operator(1, '==', 1); - assert.operator(1, '<=', 1); - assert.operator(1, '>=', 1); - assert.operator(1, '!=', 2); - assert.operator(1, '!==', 2); - - err(function () { - assert.operator(1, '=', 2); - }, 'Invalid operator "="'); - - err(function () { - assert.operator(2, '<', 1); - }, "expected 2 to be < 1"); - - err(function () { - assert.operator(1, '>', 2); - }, "expected 1 to be > 2"); - - err(function () { - assert.operator(1, '==', 2); - }, "expected 1 to be == 2"); - - err(function () { - assert.operator(2, '<=', 1); - }, "expected 2 to be <= 1"); - - err(function () { - assert.operator(1, '>=', 2); - }, "expected 1 to be >= 2"); - - err(function () { - assert.operator(1, '!=', 1); - }, "expected 1 to be != 1"); - - err(function () { - assert.operator(1, '!==', '1'); - }, "expected 1 to be !== \'1\'"); - }); - - test('closeTo', function () { - assert.closeTo(1.5, 1.0, 0.5); - assert.closeTo(10, 20, 20); - assert.closeTo(-10, 20, 30); - - err(function () { - assert.closeTo(2, 1.0, 0.5); - }, "expected 2 to be close to 1 +/- 0.5"); - - err(function () { - assert.closeTo(-10, 20, 29); - }, "expected -10 to be close to 20 +/- 29"); - }); - - test('members', function () { - assert.includeMembers([1, 2, 3], [2, 3]); - assert.includeMembers([1, 2, 3], []); - assert.includeMembers([1, 2, 3], [3]); - - err(function () { - assert.includeMembers([5, 6], [7, 8]); - }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); - - err(function () { - assert.includeMembers([5, 6], [5, 6, 0]); - }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); - }); - - test('memberEquals', function () { - assert.sameMembers([], []); - assert.sameMembers([1, 2, 3], [3, 2, 1]); - assert.sameMembers([4, 2], [4, 2]); - - err(function () { - assert.sameMembers([], [1, 2]); - }, 'expected [] to have the same members as [ 1, 2 ]'); - - err(function () { - assert.sameMembers([1, 54], [6, 1, 54]); - }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); - }); - -}); diff --git a/chai/chai-assert.d.ts b/chai/chai-assert.d.ts deleted file mode 100644 index 30ae2deb7..000000000 --- a/chai/chai-assert.d.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Type definitions for chai v1.9.0 assert style -// Project: http://chaijs.com/ -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module chai { - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } - export function use(plugin: any): void; - - export var Assertion: ChaiAssertion; - export var assert: Assert; - export var config: ChaiConfig; - - export interface ChaiConfig { - includeStack: boolean; - } - - export interface ChaiAssertion { - // what? - } - - export interface Assert { - (express: any, msg?: string):void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string):void; - - ok(val: any, msg?: string):void; - notOk(val: any, msg?: string):void; - - equal(act: any, exp: any, msg?: string):void; - notEqual(act: any, exp: any, msg?: string):void; - - strictEqual(act: any, exp: any, msg?: string):void; - notStrictEqual(act: any, exp: any, msg?: string):void; - - deepEqual(act: any, exp: any, msg?: string):void; - notDeepEqual(act: any, exp: any, msg?: string):void; - - isTrue(val: any, msg?: string):void; - isFalse(val: any, msg?: string):void; - - isNull(val: any, msg?: string):void; - isNotNull(val: any, msg?: string):void; - - isUndefined(val: any, msg?: string):void; - isDefined(val: any, msg?: string):void; - - isFunction(val: any, msg?: string):void; - isNotFunction(val: any, msg?: string):void; - - isObject(val: any, msg?: string):void; - isNotObject(val: any, msg?: string):void; - - isArray(val: any, msg?: string):void; - isNotArray(val: any, msg?: string):void; - - isString(val: any, msg?: string):void; - isNotString(val: any, msg?: string):void; - - isNumber(val: any, msg?: string):void; - isNotNumber(val: any, msg?: string):void; - - isBoolean(val: any, msg?: string):void; - isNotBoolean(val: any, msg?: string):void; - - typeOf(val: any, type: string, msg?: string):void; - notTypeOf(val: any, type: string, msg?: string):void; - - instanceOf(val: any, type: Function, msg?: string):void; - notInstanceOf(val: any, type: Function, msg?: string):void; - - include(exp: string, inc: any, msg?: string):void; - include(exp: any[], inc: any, msg?: string):void; - - notInclude(exp: string, inc: any, msg?: string):void; - notInclude(exp: any[], inc: any, msg?: string):void; - - match(exp: any, re: RegExp, msg?: string):void; - notMatch(exp: any, re: RegExp, msg?: string):void; - - property(obj: Object, prop: string, msg?: string):void; - notProperty(obj: Object, prop: string, msg?: string):void; - deepProperty(obj: Object, prop: string, msg?: string):void; - notDeepProperty(obj: Object, prop: string, msg?: string):void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string):void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; - - lengthOf(exp: any, len: number, msg?: string):void; - //alias frenzy - throw(fn: Function, msg?: string):void; - throw(fn: Function, regExp: RegExp):void; - throw(fn: Function, errType: Function, msg?: string):void; - throw(fn: Function, errType: Function, regExp: RegExp):void; - - throws(fn: Function, msg?: string):void; - throws(fn: Function, regExp: RegExp):void; - throws(fn: Function, errType: Function, msg?: string):void; - throws(fn: Function, errType: Function, regExp: RegExp):void; - - Throw(fn: Function, msg?: string):void; - Throw(fn: Function, regExp: RegExp):void; - Throw(fn: Function, errType: Function, msg?: string):void; - Throw(fn: Function, errType: Function, regExp: RegExp):void; - - doesNotThrow(fn: Function, msg?: string):void; - doesNotThrow(fn: Function, regExp: RegExp):void; - doesNotThrow(fn: Function, errType: Function, msg?: string):void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; - - operator(val: any, operator: string, val2: any, msg?: string):void; - closeTo(act: number, exp: number, delta: number, msg?: string):void; - - sameMembers(set1: any[], set2: any[], msg?: string):void; - includeMembers(set1: any[], set2: any[], msg?: string):void; - - ifError(val: any, msg?: string):void; - } -} - -//browser global -declare var assert:chai.Assert; diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index b559c515d..98d75e8ae 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,6 +1,7 @@ /// var expect = chai.expect; +var assert = chai.assert; declare var err: Function; function chaiVersion() { @@ -767,3 +768,623 @@ function members() { expect([5, 4]).not.members([6, 3]); expect([5, 4]).not.members([5, 4, 2]); } + +//tdd +declare function suite(description: string, action: Function):void; +declare function test(description: string, action: Function):void; + +interface FieldObj { + field: any; +} +class Foo { + constructor() { + + } +} + +class CrashyObject { + inspect (): void { + throw new Error("Arg's inspect() called even though the test passed"); + } +} + +suite('assert', function () { + + test('assert', function () { + var foo = 'bar'; + assert(foo == 'bar', "expected foo to equal `bar`"); + + err(function () { + assert(foo == 'baz', "expected foo to equal `bar`"); + }, "expected foo to equal `bar`"); + }); + + test('isTrue', function () { + assert.isTrue(true); + + err(function () { + assert.isTrue(false); + }, "expected false to be true"); + + err(function () { + assert.isTrue(1); + }, "expected 1 to be true"); + + err(function () { + assert.isTrue('test'); + }, "expected 'test' to be true"); + }); + + test('ok', function () { + assert.ok(true); + assert.ok(1); + assert.ok('test'); + + err(function () { + assert.ok(false); + }, "expected false to be truthy"); + + err(function () { + assert.ok(0); + }, "expected 0 to be truthy"); + + err(function () { + assert.ok(''); + }, "expected '' to be truthy"); + }); + + test('isFalse', function () { + assert.isFalse(false); + + err(function () { + assert.isFalse(true); + }, "expected true to be false"); + + err(function () { + assert.isFalse(0); + }, "expected 0 to be false"); + }); + + test('equal', function () { + var foo: any; + assert.equal(foo, undefined); + }); + + test('typeof / notTypeOf', function () { + assert.typeOf('test', 'string'); + assert.typeOf(true, 'boolean'); + assert.typeOf(5, 'number'); + + err(function () { + assert.typeOf(5, 'string'); + }, "expected 5 to be a string"); + + }); + + test('notTypeOf', function () { + assert.notTypeOf('test', 'number'); + + err(function () { + assert.notTypeOf(5, 'number'); + }, "expected 5 not to be a number"); + }); + + test('instanceOf', function () { + assert.instanceOf(new Foo(), Foo); + + err(function () { + assert.instanceOf(5, Foo); + }, "expected 5 to be an instance of Foo"); + assert.instanceOf(new CrashyObject(), CrashyObject); + }); + + test('notInstanceOf', function () { + assert.notInstanceOf(new Foo(), String); + + err(function () { + assert.notInstanceOf(new Foo(), Foo); + }, "expected {} to not be an instance of Foo"); + }); + + test('isObject', function () { + assert.isObject({}); + assert.isObject(new Foo()); + + err(function () { + assert.isObject(true); + }, "expected true to be an object"); + + err(function () { + assert.isObject(Foo); + }, "expected [Function: Foo] to be an object"); + + err(function () { + assert.isObject('foo'); + }, "expected 'foo' to be an object"); + }); + + test('isNotObject', function () { + assert.isNotObject(5); + + err(function () { + assert.isNotObject({}); + }, "expected {} not to be an object"); + }); + + test('notEqual', function () { + assert.notEqual(3, 4); + + err(function () { + assert.notEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('strictEqual', function () { + assert.strictEqual('foo', 'foo'); + + err(function () { + assert.strictEqual('5', 5); + }, "expected \'5\' to equal 5"); + }); + + test('notStrictEqual', function () { + assert.notStrictEqual(5, '5'); + + err(function () { + assert.notStrictEqual(5, 5); + }, "expected 5 to not equal 5"); + }); + + test('deepEqual', function () { + assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); + + err(function () { + assert.deepEqual({tea: 'chai'}, {tea: 'black'}); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + + var obja = Object.create({ tea: 'chai' }) + , objb = Object.create({ tea: 'chai' }); + + assert.deepEqual(obja, objb); + + var obj1 = Object.create({tea: 'chai'}) + , obj2 = Object.create({tea: 'black'}); + + err(function () { + assert.deepEqual(obj1, obj2); + }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); + }); + + test('deepEqual (ordering)', function () { + var a = { a: 'b', c: 'd' } + , b = { c: 'd', a: 'b' }; + assert.deepEqual(a, b); + }); + + test('deepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepEqual(circularObject, secondCircularObject); + + err(function () { + secondCircularObject.field2 = secondCircularObject; + assert.deepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); + }); + + test('notDeepEqual', function () { + assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); + err(function () { + assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); + }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); + }); + + test('notDeepEqual (circular)', function () { + var circularObject:any = {} + , secondCircularObject:any = { tea: 'jasmine' }; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.notDeepEqual(circularObject, secondCircularObject); + + err(function () { + delete secondCircularObject.tea; + assert.notDeepEqual(circularObject, secondCircularObject); + }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); + }); + + test('isNull', function () { + assert.isNull(null); + + err(function () { + assert.isNull(undefined); + }, "expected undefined to equal null"); + }); + + test('isNotNull', function () { + assert.isNotNull(undefined); + + err(function () { + assert.isNotNull(null); + }, "expected null to not equal null"); + }); + + test('isUndefined', function () { + assert.isUndefined(undefined); + + err(function () { + assert.isUndefined(null); + }, "expected null to equal undefined"); + }); + + test('isDefined', function () { + assert.isDefined(null); + + err(function () { + assert.isDefined(undefined); + }, "expected undefined to not equal undefined"); + }); + + test('isFunction', function () { + var func = function () { + }; + assert.isFunction(func); + + err(function () { + assert.isFunction({}); + }, "expected {} to be a function"); + }); + + test('isNotFunction', function () { + assert.isNotFunction(5); + + err(function () { + assert.isNotFunction(function () { + }); + }, "expected [Function] not to be a function"); + }); + + test('isArray', function () { + assert.isArray([]); + assert.isArray(new Array()); + + err(function () { + assert.isArray({}); + }, "expected {} to be an array"); + }); + + test('isNotArray', function () { + assert.isNotArray(3); + + err(function () { + assert.isNotArray([]); + }, "expected [] not to be an array"); + + err(function () { + assert.isNotArray(new Array()); + }, "expected [] not to be an array"); + }); + + test('isString', function () { + assert.isString('Foo'); + assert.isString(new String('foo')); + + err(function () { + assert.isString(1); + }, "expected 1 to be a string"); + }); + + test('isNotString', function () { + assert.isNotString(3); + assert.isNotString([ 'hello' ]); + + err(function () { + assert.isNotString('hello'); + }, "expected 'hello' not to be a string"); + }); + + test('isNumber', function () { + assert.isNumber(1); + assert.isNumber(Number('3')); + + err(function () { + assert.isNumber('1'); + }, "expected \'1\' to be a number"); + }); + + test('isNotNumber', function () { + assert.isNotNumber('hello'); + assert.isNotNumber([ 5 ]); + + err(function () { + assert.isNotNumber(4); + }, "expected 4 not to be a number"); + }); + + test('isBoolean', function () { + assert.isBoolean(true); + assert.isBoolean(false); + + err(function () { + assert.isBoolean('1'); + }, "expected \'1\' to be a boolean"); + }); + + test('isNotBoolean', function () { + assert.isNotBoolean('true'); + + err(function () { + assert.isNotBoolean(true); + }, "expected true not to be a boolean"); + + err(function () { + assert.isNotBoolean(false); + }, "expected false not to be a boolean"); + }); + + test('include', function () { + assert.include('foobar', 'bar'); + assert.include([ 1, 2, 3], 3); + + err(function () { + assert.include('foobar', 'baz'); + }, "expected \'foobar\' to contain \'baz\'"); + + err(function () { + assert.include(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('notInclude', function () { + assert.notInclude('foobar', 'baz'); + assert.notInclude([ 1, 2, 3 ], 4); + + err(function () { + assert.notInclude('foobar', 'bar'); + }, "expected \'foobar\' to not contain \'bar\'"); + + err(function () { + assert.notInclude(undefined, 'bar'); + }, "expected an array or string"); + }); + + test('lengthOf', function () { + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf('foobar', 6); + + err(function () { + assert.lengthOf('foobar', 5); + }, "expected 'foobar' to have a length of 5 but got 6"); + + err(function () { + assert.lengthOf(1, 5); + }, "expected 1 to have a property \'length\'"); + }); + + test('match', function () { + assert.match('foobar', /^foo/); + assert.notMatch('foobar', /^bar/); + + err(function () { + assert.match('foobar', /^bar/i); + }, "expected 'foobar' to match /^bar/i"); + + err(function () { + assert.notMatch('foobar', /^foo/i); + }, "expected 'foobar' not to match /^foo/i"); + }); + + test('property', function () { + var obj = { foo: { bar: 'baz' } }; + var simpleObj = { foo: 'bar' }; + assert.property(obj, 'foo'); + assert.deepProperty(obj, 'foo.bar'); + assert.notProperty(obj, 'baz'); + assert.notProperty(obj, 'foo.bar'); + assert.notDeepProperty(obj, 'foo.baz'); + assert.deepPropertyVal(obj, 'foo.bar', 'baz'); + assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); + + err(function () { + assert.property(obj, 'baz'); + }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); + + err(function () { + assert.deepProperty(obj, 'foo.baz'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); + + err(function () { + assert.notProperty(obj, 'foo'); + }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); + + err(function () { + assert.notDeepProperty(obj, 'foo.bar'); + }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); + + err(function () { + assert.propertyVal(simpleObj, 'foo', 'ball'); + }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); + + err(function () { + assert.deepPropertyVal(obj, 'foo.bar', 'ball'); + }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); + + err(function () { + assert.propertyNotVal(simpleObj, 'foo', 'bar'); + }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); + + err(function () { + assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); + }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); + }); + + test('throws', function () { + assert.throws(function () { + throw new Error('foo'); + }); + assert.throws(function () { + throw new Error('bar'); + }, 'bar'); + assert.throws(function () { + throw new Error('bar'); + }, /bar/); + assert.throws(function () { + throw new Error('bar'); + }, Error); + assert.throws(function () { + throw new Error('bar'); + }, Error, 'bar'); + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, Error, 'bar'); + }, "expected [Function] to throw error including 'bar' but got 'foo'") + + err(function () { + assert.throws(function () { + throw new Error('foo') + }, TypeError, 'bar'); + }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") + + err(function () { + assert.throws(function () { + }); + }, "expected [Function] to throw an error"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, 'bar'); + }, "expected [Function] to throw error including 'bar' but got ''"); + + err(function () { + assert.throws(function () { + throw new Error('') + }, /bar/); + }, "expected [Function] to throw error matching /bar/ but got ''"); + }); + + test('doesNotThrow', function () { + assert.doesNotThrow(function () { + }); + assert.doesNotThrow(function () { + }, 'foo'); + + err(function () { + assert.doesNotThrow(function () { + throw new Error('foo'); + }); + }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); + }); + + test('ifError', function () { + assert.ifError(false); + assert.ifError(null); + assert.ifError(undefined); + + err(function () { + assert.ifError('foo'); + }, "expected \'foo\' to be falsy"); + }); + + test('operator', function () { + assert.operator(1, '<', 2); + assert.operator(2, '>', 1); + assert.operator(1, '==', 1); + assert.operator(1, '<=', 1); + assert.operator(1, '>=', 1); + assert.operator(1, '!=', 2); + assert.operator(1, '!==', 2); + + err(function () { + assert.operator(1, '=', 2); + }, 'Invalid operator "="'); + + err(function () { + assert.operator(2, '<', 1); + }, "expected 2 to be < 1"); + + err(function () { + assert.operator(1, '>', 2); + }, "expected 1 to be > 2"); + + err(function () { + assert.operator(1, '==', 2); + }, "expected 1 to be == 2"); + + err(function () { + assert.operator(2, '<=', 1); + }, "expected 2 to be <= 1"); + + err(function () { + assert.operator(1, '>=', 2); + }, "expected 1 to be >= 2"); + + err(function () { + assert.operator(1, '!=', 1); + }, "expected 1 to be != 1"); + + err(function () { + assert.operator(1, '!==', '1'); + }, "expected 1 to be !== \'1\'"); + }); + + test('closeTo', function () { + assert.closeTo(1.5, 1.0, 0.5); + assert.closeTo(10, 20, 20); + assert.closeTo(-10, 20, 30); + + err(function () { + assert.closeTo(2, 1.0, 0.5); + }, "expected 2 to be close to 1 +/- 0.5"); + + err(function () { + assert.closeTo(-10, 20, 29); + }, "expected -10 to be close to 20 +/- 29"); + }); + + test('members', function () { + assert.includeMembers([1, 2, 3], [2, 3]); + assert.includeMembers([1, 2, 3], []); + assert.includeMembers([1, 2, 3], [3]); + + err(function () { + assert.includeMembers([5, 6], [7, 8]); + }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); + + err(function () { + assert.includeMembers([5, 6], [5, 6, 0]); + }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); + }); + + test('memberEquals', function () { + assert.sameMembers([], []); + assert.sameMembers([1, 2, 3], [3, 2, 1]); + assert.sameMembers([4, 2], [4, 2]); + + err(function () { + assert.sameMembers([], [1, 2]); + }, 'expected [] to have the same members as [ 1, 2 ]'); + + err(function () { + assert.sameMembers([1, 54], [6, 1, 54]); + }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); + }); + +}); diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 058d55196..fc767c639 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,11 +1,25 @@ // Type definitions for chai 1.7.2 // Project: http://chaijs.com/ -// Definitions by: Jed Hunsaker +// Definitions by: Jed Hunsaker , Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module chai { + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } function expect(target: any, message?: string): Expect; + + export var assert: Assert; + export var config: Config; + + export interface Config { + includeStack: boolean; + } // Provides a way to extend the internals of Chai function use(fn: (chai: any, utils: any) => void): any; @@ -161,6 +175,107 @@ declare module chai { (constructor: Function, expected?: string, message?: string): Expect; (constructor: Function, expected?: RegExp, message?: string): Expect; } + + export interface Assert { + (express: any, msg?: string):void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string):void; + + ok(val: any, msg?: string):void; + notOk(val: any, msg?: string):void; + + equal(act: any, exp: any, msg?: string):void; + notEqual(act: any, exp: any, msg?: string):void; + + strictEqual(act: any, exp: any, msg?: string):void; + notStrictEqual(act: any, exp: any, msg?: string):void; + + deepEqual(act: any, exp: any, msg?: string):void; + notDeepEqual(act: any, exp: any, msg?: string):void; + + isTrue(val: any, msg?: string):void; + isFalse(val: any, msg?: string):void; + + isNull(val: any, msg?: string):void; + isNotNull(val: any, msg?: string):void; + + isUndefined(val: any, msg?: string):void; + isDefined(val: any, msg?: string):void; + + isFunction(val: any, msg?: string):void; + isNotFunction(val: any, msg?: string):void; + + isObject(val: any, msg?: string):void; + isNotObject(val: any, msg?: string):void; + + isArray(val: any, msg?: string):void; + isNotArray(val: any, msg?: string):void; + + isString(val: any, msg?: string):void; + isNotString(val: any, msg?: string):void; + + isNumber(val: any, msg?: string):void; + isNotNumber(val: any, msg?: string):void; + + isBoolean(val: any, msg?: string):void; + isNotBoolean(val: any, msg?: string):void; + + typeOf(val: any, type: string, msg?: string):void; + notTypeOf(val: any, type: string, msg?: string):void; + + instanceOf(val: any, type: Function, msg?: string):void; + notInstanceOf(val: any, type: Function, msg?: string):void; + + include(exp: string, inc: any, msg?: string):void; + include(exp: any[], inc: any, msg?: string):void; + + notInclude(exp: string, inc: any, msg?: string):void; + notInclude(exp: any[], inc: any, msg?: string):void; + + match(exp: any, re: RegExp, msg?: string):void; + notMatch(exp: any, re: RegExp, msg?: string):void; + + property(obj: Object, prop: string, msg?: string):void; + notProperty(obj: Object, prop: string, msg?: string):void; + deepProperty(obj: Object, prop: string, msg?: string):void; + notDeepProperty(obj: Object, prop: string, msg?: string):void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string):void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + + lengthOf(exp: any, len: number, msg?: string):void; + //alias frenzy + throw(fn: Function, msg?: string):void; + throw(fn: Function, regExp: RegExp):void; + throw(fn: Function, errType: Function, msg?: string):void; + throw(fn: Function, errType: Function, regExp: RegExp):void; + + throws(fn: Function, msg?: string):void; + throws(fn: Function, regExp: RegExp):void; + throws(fn: Function, errType: Function, msg?: string):void; + throws(fn: Function, errType: Function, regExp: RegExp):void; + + Throw(fn: Function, msg?: string):void; + Throw(fn: Function, regExp: RegExp):void; + Throw(fn: Function, errType: Function, msg?: string):void; + Throw(fn: Function, errType: Function, regExp: RegExp):void; + + doesNotThrow(fn: Function, msg?: string):void; + doesNotThrow(fn: Function, regExp: RegExp):void; + doesNotThrow(fn: Function, errType: Function, msg?: string):void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; + + operator(val: any, operator: string, val2: any, msg?: string):void; + closeTo(act: number, exp: number, delta: number, msg?: string):void; + + sameMembers(set1: any[], set2: any[], msg?: string):void; + includeMembers(set1: any[], set2: any[], msg?: string):void; + + ifError(val: any, msg?: string):void; + } } declare module "chai" { diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index df5058f20..cd0be3593 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,7 +1,6 @@ // Type definitions for Cheerio v0.17.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little -// Definitions by: VILIC VANE +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Cheerio { @@ -190,6 +189,11 @@ interface CheerioStatic { root(): Cheerio; contains(container: CheerioElement, contained: CheerioElement): boolean; parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[]; + + html(options?: CheerioOptionsInterface): string; + html(selector: string, options?: CheerioOptionsInterface): string; + html(element: Cheerio, options?: CheerioOptionsInterface): string; + html(element: CheerioElement, options?: CheerioOptionsInterface): string; } interface CheerioElement { diff --git a/chroma-js/chroma-js-tests.ts b/chroma-js/chroma-js-tests.ts new file mode 100644 index 000000000..3240ac11f --- /dev/null +++ b/chroma-js/chroma-js-tests.ts @@ -0,0 +1,120 @@ +/// + +function test_chroma() { + chroma("red"); + chroma("#ff0000"); + chroma("#f00"); + chroma("FF0000"); + chroma(255, 0, 0); + chroma([255, 0, 0]); + chroma(0, 1, 0.5, 'hsl'); + chroma([0, 1, 0.5], 'hsl'); + chroma(0, 1, 1, 'hsv'); + chroma("rgb(255,0,0)"); + chroma("rgb(100%,0%,0%)"); + chroma("hsl(0,100%,50%)"); + chroma(53.24, 80.09, 67.20, 'lab'); + chroma(53.24, 104.55, 40, 'lch'); + chroma(1, 0, 0, 'gl'); + + chroma.hex("#ff0000"); + chroma.hex("red"); + chroma.hex("rgb(255, 0, 0)"); + + chroma.rgb(255, 0, 0); + chroma.hsl(0, 1, 0.5); + chroma.hsv(120, 0.5, 0.5); + chroma.lab(53.24, 80.09, 67.20); + chroma.lch(53.24, 104.55, 40); + chroma.gl(1, 0, 0); + + chroma.interpolate('white', 'black', 0) // #ffffff + chroma.interpolate('white', 'black', 1) // #000000 + chroma.interpolate('white', 'black', 0.5) // #7f7f7f + chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080 + chroma.interpolate('white', 'black', 0.5, 'lab') // #777777 + + chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)" + + var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']); + bezInterpolator(0).hex() // #ffffff + bezInterpolator(0.33).hex() // #ffcc67 + bezInterpolator(0.66).hex() // #b65f1a + bezInterpolator(1).hex() // #000000 + + chroma.luminance('black') // 0 + chroma.luminance('white') // 1 + chroma.luminance('#ff0000') // 0.2126 + + chroma.contrast('white', 'navy') // 16.00 – ok + chroma.contrast('white', 'yellow') // 1.07 – not ok! +} + +function test_color() { + chroma('red').hex() // "#FF0000"" + chroma('red').rgb() // [255, 0, 0] + chroma('red').hsv() // [0, 1, 1] + chroma('red').hsl() // [0, 1, 0.5] + chroma('red').lab() // [53.2407, 80.0924, 67.2031] + chroma('red').lch() // [53.2407, 104.5517, 39.9990] + chroma('red').rgba() // [255, 0, 0, 1] + chroma('red').css() // "rgb(255,0,0)" + chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)" + chroma('red').css('hsl') // "hsl(0,100%,50%)" + chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)" + chroma('blue').css('hsla') // "hsla(240,100%,50%,1)" + + var red = chroma('red'); + red.alpha(0.5); + red.css(); // rgba(255,0,0,0.5); + + chroma('red').darken().hex() // #BC0000 + chroma('red').brighten().hex() // #FF603B + chroma('#eecc99').saturate().hex() // #fcc973 + chroma('red').desaturate().hex() // #ec3d23 + + chroma('black').luminance() // 0 + chroma('white').luminance() // 1 + chroma('red').luminance() // 0.2126 +} + +function test_scale() { + var scale = chroma.scale(['lightyellow', 'navy']); + scale(0.5); // #7F7FB0 + + chroma.scale('RdYlBu'); + + var col = scale(0.5); + col.hex(); // #7F7FB0 + col.rgb(); // [127.5, 127.5, 176] + + scale = chroma.scale(['lightyellow', 'navy']).out('hex'); + scale(0.5); // "#7F7FB0" + + var scale = chroma.scale(['lightyellow', 'navy']); + scale.mode('hsv')(0.5); // #54C08A + scale.mode('hsl')(0.5); // #31FF98 + scale.mode('lab')(0.5); // #967CB2 + scale.mode('lch')(0.5); // #D26662 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]); + scale(200); // #7F7FB0 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]); + scale(98); // #7F7FB0 + scale(99); // #7F7FB0 + scale(100); // #AAAAC0 + scale(101); // #AAAAC0 + + chroma.scale(['#eee', '#900']).domain([0, 400], 7); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means'); + chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100] + + chroma.scale().range(['lightyellow', 'navy']); + + chroma.scale(['lightyellow', 'navy']).correctLightness(true); + + chroma.scale('RdYlGn').domain([0,1], 5).colors() +} diff --git a/chroma-js/chroma-js.d.ts b/chroma-js/chroma-js.d.ts new file mode 100644 index 000000000..94b32ae81 --- /dev/null +++ b/chroma-js/chroma-js.d.ts @@ -0,0 +1,317 @@ +// Type definitions for Chroma.js v0.5.6 +// Project: https://github.com/gka/chroma.js +// Definitions by: Sebastian Brückner +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * Chroma.js is a tiny library for all kinds of color conversions and color scales. + */ +declare module Chroma { + + export interface ChromaStatic { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + * @return the color object. + */ + (color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (values: number[], colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + color(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: string): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: string): number; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + css(color: string): Color; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.css(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + hex(color: string): Color; + + rgb(red: number, green: number, blue: number, alpha?: number): Color; + hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; + hsv(hue: number, saturation: number, value: number, alpha?: number): Color; + lab(lightness: number, a: number, b: number, alpha?: number): Color; + lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; + gl(red: number, green: number, blue: number, alpha?: number): Color; + + interpolate: InterpolateFunction; + mix: InterpolateFunction; + + luminance(color: Color): number; + luminance(color: string): number; + + /** + * Creates a color scale using a pre-defined color scale. + * + * @param name The name of the color scale. + * @return the resulting color scale. + */ + scale(name: string): Scale; + + /** + * Creates a color scale function from the given set of colors. + * + * @param colors An Array of at least two color names or hex values. + * @return the resulting color scale. + */ + scale(colors?: string[]): Scale; + + scales: PredefinedScales; + } + + interface InterpolateFunction { + (color1: Color, color2: Color, f: number, mode?: string): Color; + (color1: Color, color2: string, f: number, mode?: string): Color; + (color1: string, color2: Color, f: number, mode?: string): Color; + (color1: string, color2: string, f: number, mode?: string): Color; + + bezier(colors: any[]): (t: number) => Color; + } + + interface PredefinedScales { + [key: string]: Scale; + + cool: Scale; + hot: Scale; + } + + export interface Color { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + */ + new(color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. + * + * @param a + * @param b + * @param c + * @param alpha The alpha value of the color. + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(values: number[], colorSpace: string): Color; + + /** + * Convert this color to CSS hex representation. + * + * @return this color's hex representation. + */ + hex(): string; + + /** + * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). + */ + luminance(): number; + + /** + * @return the X11 name of this color or its hex value if it does not have a name. + */ + name(): string; + + /** + * @return the alpha value of the color. + */ + alpha(): number; + + /** + * Set the alpha value. + * + * @param alpha The alpha value. + * @return this + */ + alpha(alpha: number): Color; + + css(mode?: string): string; + + interpolate(color: Color, f: number, mode?: string): Color; + interpolate(color: string, f: number, mode?: string): Color; + + premultiply(): Color; + + rgb(): number[]; + rgba(): number[]; + hsl(): number[]; + hsv(): number[]; + lab(): number[]; + lch(): number[]; + hsi(): number[]; + gl(): number[]; + + darken(amount?: number): Color; + darker(amount: number): Color; + brighten(amount?: number): Color; + brighter(amount: number): Color; + saturate(amount?: number): Color; + desaturate(amount?: number): Color; + + toString(): string; + } + + export interface Scale { + /** + * Interpolate a color using the currently set range and domain. + * + * @param value The value to use for interpolation. + * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). + */ + (value: number): any; + + /** + * Retreive all possible colors generated by this scale if it has distinct classes. + * + * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". + * @return an array of colors in the type specified by mode. + */ + colors(mode?: string): any[]; + + correctLightness(): boolean; + + /** + * Enable or disable automatic lightness correction of this scale. + * + * @param Whether to enable or disable automatic lightness correction. + * @return this + */ + correctLightness(enable: boolean): Scale; + + /** + * Get the current domain. + * + * @return The current domain. + */ + domain(): number[]; + + /** + * Set the domain. + * + * @param domain An Array of at least two numbers (min and max). + * @param classes The number of fixed classes to create between min and max. + * @param mode The scale to use. Examples: log, quantiles, k-means. + * @return this + */ + domain(domain: number[], classes?: number, mode?: string): Scale; + + /** + * Specify in which color space the colors should be interpolated. Defaults to "rgb". + * You can use any of the following spaces: rgb, hsv, hsl, lab, lch + * + * @param colorSpace The color space to use for interpolation. + * @return this + */ + mode(colorSpace: string): Scale; + + /** + * Set the output mode of this Scale. + * + * @param mode The output mode to use. Must be one of Color's getters. + * @return this + */ + out(mode: string): Scale; + + /** + * Set the color range after initialization. + * + * @param colors An Array of at least two color names or hex values. + * @return this + */ + range(colors: string[]): Scale; + } + +} + +declare var chroma: Chroma.ChromaStatic; diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index 0ae0ae2af..12dc7b97d 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -24,4 +24,253 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa chrome.app.runtime.onRestarted.addListener(function () { return; }); // Get Current Window -var currentWindow: cwindow.AppWindow = chrome.app.window.current(); \ No newline at end of file +var currentWindow: cwindow.AppWindow = chrome.app.window.current(); + +// Sockets +// https://developer.chrome.com/apps/sockets_tcp +function test_socketsTcp(): void { + var socketId: number; + var properties: chrome.sockets.tcp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcp.update(socketId, properties); + chrome.sockets.tcp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcp.setPaused(socketId, true); + chrome.sockets.tcp.setPaused(socketId, true, () => { }); + + // setKeepAlive + chrome.sockets.tcp.setKeepAlive(socketId, true, (result: number) => { }); + chrome.sockets.tcp.setKeepAlive(socketId, true, 0, (result: number) => { }); + + // setNoDelay + chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { }); + + // connect + chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // send + chrome.sockets.tcp.send(socketId, buffer, (info: chrome.sockets.tcp.SendInfo) => { }); + + // close + chrome.sockets.tcp.close(socketId); + chrome.sockets.tcp.close(socketId, () => { }); + + // getInfo + chrome.sockets.tcp.getInfo(socketId, (info: chrome.sockets.tcp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpEvents(): void { + chrome.sockets.tcp.onReceive.addListener((info: chrome.sockets.tcp.ReceiveEventArgs) => { }); + chrome.sockets.tcp.onReceiveError.addListener((info: chrome.sockets.tcp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsTcpTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true, + connected: false + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; + socketInfo.peerAddress = "192.168.0.3"; + socketInfo.peerPort = 1000; +} + +// https://developer.chrome.com/apps/sockets_udp +function test_socketsUdp(): void { + var socketId: number; + var properties: chrome.sockets.udp.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.udp.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.udp.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.udp.update(socketId, properties); + chrome.sockets.udp.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.udp.setPaused(socketId, true); + chrome.sockets.udp.setPaused(socketId, true, () => { }); + + // bind + chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { }); + + // send + chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { }); + + // joinGroup + chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { }); + + // leaveGroup + chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { }); + + // setMulticastTimeToLive + chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { }); + + // setMulticastLoopbackMode + chrome.sockets.udp.setMulticastLoopbackMode(socketId, true, (result: number) => { }); + + // getJoinedGroups + chrome.sockets.udp.getJoinedGroups(socketId, (groups: string[]) => { }); +} + +function test_socketsUdpEvents(): void { + chrome.sockets.udp.onReceive.addListener((info: chrome.sockets.udp.ReceiveEventArgs) => { }); + chrome.sockets.udp.onReceiveError.addListener((info: chrome.sockets.udp.ReceiveErrorEventArgs) => { }); +} + +function testSocketsUdpTypes(): void { + // SocketProperties + var properties: chrome.sockets.udp.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test", + bufferSize: 1024 + }; + + // SocketInfo + var socketInfo: chrome.sockets.udp.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.bufferSize = 1024; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} + +// https://developer.chrome.com/apps/sockets_tcpServer +function test_socketsTcpServer(): void { + var socketId: number; + var properties: chrome.sockets.tcpServer.SocketProperties = {}; + var buffer: ArrayBuffer = new ArrayBuffer(256); + + // create + chrome.sockets.tcpServer.create((info) => { + socketId = info.socketId; + }); + + chrome.sockets.tcpServer.create(properties, (info) => { + socketId = info.socketId; + }); + + // update + chrome.sockets.tcpServer.update(socketId, properties); + chrome.sockets.tcpServer.update(socketId, properties, () => { }); + + // setPaused + chrome.sockets.tcpServer.setPaused(socketId, true); + chrome.sockets.tcpServer.setPaused(socketId, true, () => { }); + + // listen + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { }); + chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { }); + + // disconnect + chrome.sockets.tcp.disconnect(socketId); + chrome.sockets.tcp.disconnect(socketId, () => { }); + + // close + chrome.sockets.udp.close(socketId); + chrome.sockets.udp.close(socketId, () => { }); + + // getInfo + chrome.sockets.udp.getInfo(socketId, (info: chrome.sockets.udp.SocketInfo) => { }); + + // getSockets + chrome.sockets.tcp.getSockets(socketId, (infos: chrome.sockets.tcp.SocketInfo[]) => { }); +} + +function test_socketsTcpServerEvents(): void { + chrome.sockets.tcpServer.onAccept.addListener((info: chrome.sockets.tcpServer.AcceptEventArgs) => { }); + chrome.sockets.tcpServer.onAcceptError.addListener((info: chrome.sockets.tcpServer.AcceptErrorEventArgs) => { }); +} + +function testSocketsTcpServerTypes(): void { + // SocketProperties + var properties: chrome.sockets.tcpServer.SocketProperties; + + properties = { + }; + + properties = { + persistent: true, + name: "test" + }; + + // SocketInfo + var socketInfo: chrome.sockets.tcpServer.SocketInfo; + + socketInfo = { + socketId: 1, + persistent: true, + paused: true + }; + + socketInfo.name = "test"; + socketInfo.localAddress = "192.168.0.2"; + socketInfo.localPort = 8000; +} diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index ad319394f..830b26e4f 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Adam Lay +// Definitions by: Adam Lay , MIZUNE Pine // Definitions: https://github.com/borisyankov/DefinitelyTyped //////////////////// @@ -93,3 +93,189 @@ declare module chrome.app.window { var onMinimized: WindowEvent; var onRestored: WindowEvent; } + + +//////////////////// +// Sockets +//////////////////// +declare module chrome.sockets.tcp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + connected: boolean; + localAddress?: string; + localPort?: number; + peerAddress?: string; + peerPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + + export function setKeepAlive(socketId: number, + enable: boolean, callback: (result: number) => void): void; + export function setKeepAlive(socketId: number, + enable: boolean, delay: number, callback: (result: number) => void): void; + + export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; + export function connect(socketId: number, + peerAddress: string, peerPort: number, callback: (result: number) => void): void; + export function disconnect(socketId: number, callback?: () => void): void; + export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.udp { + interface CreateInfo { + socketId: number; + } + + interface SendInfo { + resultCode: number; + bytesSent?: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface ReceiveEventArgs { + socketId: number; + data: ArrayBuffer; + remoteAddress: string; + remotePort: number; + } + + interface ReceiveErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + bufferSize?: number; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + bufferSize?: number; + paused: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, + callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + + var onReceive: Event; + var onReceiveError: Event; +} + +declare module chrome.sockets.tcpServer { + interface CreateInfo { + socketId: number; + } + + interface Event { + addListener(callback: (info: T) => void): void; + } + + interface AcceptEventArgs { + socketId: number; + clientSocketId: number; + } + + interface AcceptErrorEventArgs { + socketId: number; + resultCode: number; + } + + interface SocketProperties { + persistent?: boolean; + name?: string; + } + + interface SocketInfo { + socketId: number; + persistent: boolean; + name?: string; + paused: boolean; + localAddress?: string; + localPort?: number; + } + + export function create(callback: (createInfo: CreateInfo) => void): void; + export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + + export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + + export function listen(socketId: number, address: string, + port: number, backlog: number, callback: (result: number) => void): void; + export function listen(socketId: number, address: string, + port: number, callback: (result: number) => void): void; + + export function disconnect(socketId: number, callback?: () => void): void; + export function close(socketId: number, callback?: () => void): void; + export function getInfo(socketId: number, callback: (socketInfos: SocketInfo[]) => void): void; + + var onAccept: Event; + var onAcceptError: Event; +} \ No newline at end of file diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 796635c27..e7e58dbbc 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -3,6 +3,8 @@ // Definitions by: Matthew Kimber , otiai10 // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + //////////////////// // Alarms //////////////////// @@ -294,6 +296,7 @@ declare module chrome.contextMenus { pageUrl: string; linkUrl?: string; parentMenuItemId?: any; + srcUrl?: string; } interface CreateProperties { @@ -537,6 +540,14 @@ declare module chrome.declarativeWebRequest { var onRequest: RequestedEvent; } +//////////////////// +// DesktopCapture +//////////////////// +declare module chrome.desktopCapture { + export function chooseDesktopMedia(sources: string[], targetTab?: chrome.tabs.Tab, callback?: (streamId: string) => void): void; + export function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; +} + //////////////////// // Dev Tools - Inspected Window //////////////////// @@ -843,8 +854,12 @@ declare module chrome.extension { type?: string; } + interface LastError { + message?: string; + } + var inIncognitoContext: boolean; - var lastError: Object; + var lastError: LastError; export function getBackgroundPage(): Window; export function getURL(path: string): string; @@ -1487,9 +1502,13 @@ declare module chrome.proxy { // Runtime //////////////////// declare module chrome.runtime { - var lastError: Object; + var lastError: LastError; var id: string; + interface LastError { + message?: string; + } + interface ConnectInfo { name?: string; } @@ -1737,6 +1756,27 @@ declare module chrome.socket { export function getNetworkList(callback: (result: NetworkInterface[]) => void): void; } +//////////////////// +// TabCapture +//////////////////// +declare module chrome.tabCapture { + interface CaptureInfo { + tabId: number; + status: string; + fullscreen: boolean; + } + + interface CaptureOptions { + audio?: boolean; + video?: boolean; + audioConstraints?: MediaTrackConstraints; + videoConstraints?: MediaTrackConstraints; + } + + export function capture(options: CaptureOptions, callback: (stream: LocalMediaStream) => void): void; + export function getCapturedTabs(callback: (result: CaptureInfo[]) => void): void; +} + //////////////////// // Tabs //////////////////// diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index affee3458..af4b32046 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -9,7 +9,7 @@ declare function CodeMirror(callback: (host: HTMLElement) => void , options?: Co declare module CodeMirror { export var Pass: any; - function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.Editor; + function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; var version: string; @@ -86,6 +86,11 @@ declare module CodeMirror { or the line the widget is on require the widget to be redrawn. */ function on(line: LineWidget, eventName: 'redraw', handler: () => void ): void; function off(line: LineWidget, eventName: 'redraw', handler: () => void ): void; + + /** Various CodeMirror-related objects emit events, which allow client code to react to various situations. + Handlers for such events can be registered with the on and off methods on the objects that the event fires on. + To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */ + function signal(target: any, name: string, ...args: any[]): void; interface Editor { @@ -369,6 +374,18 @@ declare module CodeMirror { on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; } + + interface EditorFromTextArea extends Editor { + + /** Copy the content of the editor into the textarea. */ + save(): void; + + /** Remove the editor, and restore the original textarea (with the editor's current content). */ + toTextArea(): void; + + /** Returns the textarea that the instance was based on. */ + getTextArea(): HTMLTextAreaElement; + } class Doc { constructor (text: string, mode?: any, firstLineNumber?: number); diff --git a/compression/compression-tests.ts b/compression/compression-tests.ts new file mode 100644 index 000000000..ecfcab432 --- /dev/null +++ b/compression/compression-tests.ts @@ -0,0 +1,10 @@ +/// + +import express = require('express'); +import compress = require('compression'); + +var app = express(); +app.use(compress()); +app.use(compress({ + threshold: 512 +})); diff --git a/compression/compression.d.ts b/compression/compression.d.ts new file mode 100644 index 000000000..00b2e0459 --- /dev/null +++ b/compression/compression.d.ts @@ -0,0 +1,20 @@ +// Type definitions for compression +// Project: https://github.com/expressjs/compression +// Definitions by: Santi Albo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "compression" { + import express = require('express'); + + module e { + interface CompressionOptions { + threshold?: number; + filter?: Function; + } + } + + function e(options?: e.CompressionOptions): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/cookie-parser/cookie-parser-tests.ts b/cookie-parser/cookie-parser-tests.ts new file mode 100644 index 000000000..94e8a9fdb --- /dev/null +++ b/cookie-parser/cookie-parser-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import cookieParser = require('cookie-parser'); + +var app = express(); +app.use(cookieParser('optional secret string')); diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts new file mode 100644 index 000000000..a4897c5e7 --- /dev/null +++ b/cookie-parser/cookie-parser.d.ts @@ -0,0 +1,12 @@ +// Type definitions for cookie-parser +// Project: https://github.com/expressjs/cookie-parser +// Definitions by: Santi Albo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "cookie-parser" { + import express = require('express'); + function e(secret?: string, options?: any): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/csurf/csurf.d.ts b/csurf/csurf.d.ts new file mode 100644 index 000000000..cc78f9599 --- /dev/null +++ b/csurf/csurf.d.ts @@ -0,0 +1,30 @@ +// Type definitions for csurf +// Project: https://www.npmjs.org/package/csurf +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + csrfToken(): string; + } +} + +declare module "csurf" { + import express = require('express'); + + function csurf(options?: { + value?: (req: express.Request) => string; + cookie?: csurf.CookieOptions; + }): express.RequestHandler; + + module csurf { + export interface CookieOptions extends express.CookieOptions { + key: string; + } + } + + export = csurf; +} + diff --git a/d3/d3.d.ts b/d3/d3.d.ts old mode 100755 new mode 100644 index 598cd9f34..a451a0de5 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -243,7 +243,7 @@ declare module D3 { * * @param map Array of objects to get the values from */ - values(map: any[]): any[]; + values(map: any): any[]; /** * List the key-value entries of an associative array. * @@ -417,7 +417,7 @@ declare module D3 { /* * The array of built-in interpolator factories */ - interpolators: Array; + interpolators: Transition.InterpolateFactory[]; /** * Layouts */ @@ -525,11 +525,11 @@ declare module D3 { /** * gets the mouse position relative to a specified container. */ - mouse(container: any): Array; + mouse(container: any): number[]; /** * gets the touch positions relative to a specified container. */ - touches(container: any): Array>; + touches(container: any): number[][]; /** * If the specified value is a function, returns the specified value. @@ -538,10 +538,12 @@ declare module D3 { functor(value: (p : R) => T): (p : R) => T; functor(value: T): (p : any) => T; - map(object?: any): Map; - set(array?: Array): Set; - dispatch(...types: Array): Dispatch; - rebind(target: any, source: any, ...names: Array): any; + map(): Map; + set(): Set; + map(object: {[key: string]: T; }): Map; + set(array: T[]): Set; + dispatch(...types: string[]): Dispatch; + rebind(target: any, source: any, ...names: any[]): any; requote(str: string): string; timer: { (funct: () => boolean, delay?: number, mark?: number): void; @@ -749,7 +751,7 @@ declare module D3 { insert: (name: string, before: string) => Selection; remove: () => Selection; empty: () => boolean; - + data: { (values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => any): UpdateSelection; (values: any[], key?: (data: any, index?: number) => any): UpdateSelection; @@ -839,23 +841,27 @@ declare module D3 { entries(values: any[]): NestKeyValue[]; } - export interface Map { + export interface Map { has(key: string): boolean; - get(key: string): any; - set(key: string, value: T): T; + get(key: string): T; + set(key: string, value: T): T; remove(key: string): boolean; - keys(): Array; - values(): Array; - entries(): Array; - forEach(func: (key: string, value: any) => void ): void; + keys(): string[]; + values(): T[]; + entries(): any[][]; // Actually of form [key: string, val: T][], but this is inexpressible in Typescript + forEach(func: (key: string, value: T) => void ): void; + empty(): boolean; + size(): number; } - export interface Set{ - has(value: any): boolean; - add(value: any): any; - remove(value: any): boolean; - values(): Array; - forEach(func: (value: any) => void ): void; + export interface Set { + has(value: T): boolean; + add(value: T): T; + remove(value: T): boolean; + values(): string[]; + forEach(func: (value: string) => void ): void; + empty(): boolean; + size(): number; } export interface Random { @@ -1128,11 +1134,11 @@ declare module D3 { /** * Runs the tree layout */ - nodes(root: GraphNode): TreeLayout; + nodes(root: GraphNode): GraphNode[]; /** * Given the specified array of nodes, such as those returned by nodes, returns an array of objects representing the links from parent to child for each node */ - links(nodes: Array): Array; + links(nodes: GraphNode[]): GraphLink[]; /** * If separation is specified, uses the specified function to compute separation between neighboring nodes. If separation is not specified, returns the current separation function */ @@ -1153,11 +1159,24 @@ declare module D3 { /** * Gets the available layout size */ - (): Array; + (): number[]; /** * Sets the available layout size */ - (size: Array): TreeLayout; + (size: number[]): TreeLayout; + }; + /** + * Gets or sets the available node size + */ + nodeSize: { + /** + * Gets the available node size + */ + (): number[]; + /** + * Sets the available node size + */ + (size: number[]): TreeLayout; }; } @@ -1221,6 +1240,21 @@ declare module D3 { target: GraphNode; } + export interface GraphNodeForce { + index?: number; + x?: number; + y?: number; + px?: number; + py?: number; + fixed?: boolean; + weight?: number; + } + + export interface GraphLinkForce { + source: GraphNodeForce; + target: GraphNodeForce; + } + export interface ForceLayout { (): ForceLayout; size: { @@ -1270,14 +1304,14 @@ declare module D3 { }; links: { - (): GraphLink[]; - (arLinks: GraphLink[]): ForceLayout; + (): GraphLinkForce[]; + (arLinks: GraphLinkForce[]): ForceLayout; }; nodes: { - (): GraphNode[]; - (arNodes: GraphNode[]): ForceLayout; + (): GraphNodeForce[]; + (arNodes: GraphNodeForce[]): ForceLayout; }; start(): ForceLayout; @@ -1289,13 +1323,13 @@ declare module D3 { } export interface BundleLayout{ - (links: Array): Array>; + (links: GraphLink[]): GraphNode[][]; } export interface ChordLayout { matrix: { - (): Array>; - (matrix: Array>): ChordLayout; + (): number[][]; + (matrix: number[][]): ChordLayout; } padding: { (): number; @@ -1313,8 +1347,8 @@ declare module D3 { (): (a: number, b: number) => number; (comparator: (a: number, b: number) => number): ChordLayout; } - chords(): Array; - groups(): Array; + chords(): GraphLink[]; + groups(): ArcDescriptor[]; } export interface ClusterLayout{ @@ -1323,18 +1357,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): ClusterLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): ClusterLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): ClusterLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; seperation: { (): (a: GraphNode, b: GraphNode) => number; (seperation: (a: GraphNode, b: GraphNode) => number): ClusterLayout; } size: { - (): Array; - (size: Array): ClusterLayout; + (): number[]; + (size: number[]): ClusterLayout; } value: { (): (node: GraphNode) => number; @@ -1348,11 +1382,11 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): HierarchyLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): HierarchyLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): HierarchyLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): HierarchyLayout; @@ -1367,21 +1401,21 @@ declare module D3 { } export interface HistogramLayout { - (values: Array, index?: number): Array; + (values: any[], index?: number): Bin[]; value: { (): (value: any) => any; (accessor: (value: any) => any): HistogramLayout } range: { - (): (value: any, index: number) => Array; - (range: (value: any, index: number) => Array): HistogramLayout; - (range: Array): HistogramLayout; + (): (value: any, index: number) => number[]; + (range: (value: any, index: number) => number[]): HistogramLayout; + (range: number[]): HistogramLayout; } bins: { - (): (range: Array, index: number) => Array; - (bins: (range: Array, index: number) => Array): HistogramLayout; + (): (range: any[], index: number) => number[]; + (bins: (range: any[], index: number) => number[]): HistogramLayout; (bins: number): HistogramLayout; - (bins: Array): HistogramLayout; + (bins: number[]): HistogramLayout; } frequency: { (): boolean; @@ -1395,18 +1429,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): PackLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): PackLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): PackLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): PackLayout; } size: { - (): Array; - (size: Array): PackLayout; + (): number[]; + (size: number[]): PackLayout; } padding: { (): number; @@ -1420,18 +1454,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): PackLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): PackLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): PackLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): PackLayout; } size: { - (): Array; - (size: Array): PackLayout; + (): number[]; + (size: number[]): PackLayout; } } @@ -1441,18 +1475,18 @@ declare module D3 { (comparator: (a: GraphNode, b: GraphNode) => number): TreeMapLayout; } children: { - (): (d: any, i?: number) => Array; - (children: (d: any, i?: number) => Array): TreeMapLayout; + (): (d: any, i?: number) => GraphNode[]; + (children: (d: any, i?: number) => GraphNode[]): TreeMapLayout; } - nodes(root: GraphNode): Array; - links(nodes: Array): Array; + nodes(root: GraphNode): GraphNode[]; + links(nodes: GraphNode[]): GraphLink[]; value: { (): (node: GraphNode) => number; (value: (node: GraphNode) => number): TreeMapLayout; } size: { - (): Array; - (size: Array): TreeMapLayout; + (): number[]; + (size: number[]): TreeMapLayout; } padding: { (): number; @@ -1479,7 +1513,7 @@ declare module D3 { /** * increase lightness by some exponential factor (gamma) */ - brighter(k: number): Color; + brighter(k?: number): Color; /** * decrease lightness by some exponential factor (gamma) */ @@ -1614,7 +1648,7 @@ declare module D3 { /** * The array of supported symbol types. */ - symbolTypes: Array; + symbolTypes: string[]; } export interface Symbol { @@ -1720,10 +1754,21 @@ declare module D3 { (): any[]; (values: any[]): Axis; }; - tickSubdivide(count: number): Axis; - tickSize(major?: number, minor?: number, end?: number): Axis; + tickSize: { + (): number; + (inner: number, outer?: number): Axis; + } + innerTickSize: { + (): number; + (value: number): Axis; + } + outerTickSize: { + (): number; + (value: number): Axis; + } tickFormat(formatter: (value: any) => string): Axis; + nice(count?: number): Axis; } export interface Arc { @@ -2418,9 +2463,9 @@ declare module D3 { export interface Diagonal { (datum: any, index?: number): string; projection: { - (): (datum: any, index?: number) => Array; - (proj: (datum: any) => Array): Diagonal; - (proj: (datum: any, index: number) => Array): Diagonal; + (): (datum: any, index?: number) => number[]; + (proj: (datum: any) => number[]): Diagonal; + (proj: (datum: any, index: number) => number[]): Diagonal; }; source: { (): (datum: any, index?: number) => any; @@ -2494,21 +2539,23 @@ declare module D3 { threshold(): ThresholdScale; } - export interface Scale { + export interface GenericScale { (value: any): any; domain: { - (values: any[]): Scale; + (values: any[]): S; (): any[]; }; range: { - (values: any[]): Scale; + (values: any[]): S; (): any[]; }; invertExtent?(y: any): any[]; - copy(): Scale; + copy(): S; } - export interface QuantitiveScale extends Scale { + export interface Scale extends GenericScale { } + + export interface GenericQuantitativeScale extends GenericScale { /** * Get the range value corresponding to a given domain value. * @@ -2522,60 +2569,33 @@ declare module D3 { */ invert(value: number): number; /** - * Get or set the scale's input domain. - */ - domain: { - /** - * Set the scale's input domain. - * - * @param value The input domain - */ - (values: any[]): QuantitiveScale; - /** - * Get the scale's input domain. - */ - (): any[]; - }; - /** - * get or set the scale's output range. - */ - range: { - /** - * Set the scale's output range. - * - * @param value The output range. - */ - (values: any[]): QuantitiveScale; - /** - * Get the scale's output range. - */ - (): any[]; - }; - /** * Set the scale's output range, and enable rounding. * * @param value The output range. */ - rangeRound: (values: any[]) => QuantitiveScale; + rangeRound: (values: any[]) => S; /** * get or set the scale's output interpolator. */ interpolate: { (): D3.Transition.Interpolate; - (factory: D3.Transition.Interpolate): QuantitiveScale; + (factory: D3.Transition.Interpolate): S; }; /** * enable or disable clamping of the output range. * * @param clamp Enable or disable */ - clamp(clamp: boolean): QuantitiveScale; + clamp: { + (): boolean; + (clamp: boolean): S; + } /** * extend the scale domain to nice round numbers. - * + * * @param count Optional number of ticks to exactly fit the domain */ - nice(count?: number): QuantitiveScale; + nice(count?: number): S; /** * get representative values from the input domain. * @@ -2587,23 +2607,14 @@ declare module D3 { * * @param count Aproximate representative values to return */ - tickFormat(count: number): (n: number) => string; - /** - * create a new scale from an existing scale.. - */ - copy(): QuantitiveScale; + tickFormat(count: number, format?: string): (n: number) => string; } - export interface LinearScale extends QuantitiveScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface QuantitativeScale extends GenericQuantitativeScale { } - export interface IdentityScale extends Scale { + export interface LinearScale extends GenericQuantitativeScale { } + + export interface IdentityScale extends GenericScale { /** * Get the range value corresponding to a given domain value. * @@ -2630,132 +2641,31 @@ declare module D3 { tickFormat(count: number): (n: number) => string; } - export interface SqrtScale extends QuantitiveScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface SqrtScale extends GenericQuantitativeScale { } - export interface PowScale extends QuantitiveScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface PowScale extends GenericQuantitativeScale { } - export interface LogScale extends QuantitiveScale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: number): number; - } + export interface LogScale extends GenericQuantitativeScale { } - export interface OrdinalScale extends Scale { - /** - * Get the range value corresponding to a given domain value. - * - * @param value Domain Value - */ - (value: any): any; - /** - * Get or set the scale's input domain. - */ - domain: { - /** - * Set the scale's input domain. - * - * @param value The input domain - */ - (values: any[]): OrdinalScale; - /** - * Get the scale's input domain. - */ - (): any[]; - }; - /** - * get or set the scale's output range. - */ - range: { - /** - * Set the scale's output range. - * - * @param value The output range. - */ - (values: any[]): OrdinalScale; - /** - * Get the scale's output range. - */ - (): any[]; - }; + export interface OrdinalScale extends GenericScale { rangePoints(interval: any[], padding?: number): OrdinalScale; rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; rangeBand(): number; rangeExtent(): any[]; - /** - * create a new scale from an existing scale.. - */ - copy(): OrdinalScale; } - export interface QuantizeScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantizeScale; - (): any[]; - }; - range: { - (values: any[]): QuantizeScale; - (): any[]; - }; - copy(): QuantizeScale; - } + export interface QuantizeScale extends GenericScale { } - export interface ThresholdScale extends Scale { - (value: any): any; - domain: { - (values: number[]): ThresholdScale; - (): any[]; - }; - range: { - (values: any[]): ThresholdScale; - (): any[]; - }; - copy(): ThresholdScale; - } + export interface ThresholdScale extends GenericScale { } - export interface QuantileScale extends Scale { - (value: any): any; - domain: { - (values: number[]): QuantileScale; - (): any[]; - }; - range: { - (values: any[]): QuantileScale; - (): any[]; - }; + export interface QuantileScale extends GenericScale { quantiles(): any[]; - copy(): QuantileScale; } - export interface TimeScale extends Scale { + export interface TimeScale extends GenericScale { (value: Date): number; invert(value: number): Date; - domain: { - (values: any[]): TimeScale; - (): any[]; - }; - range: { - (values: any[]): TimeScale; - (): any[]; - }; rangeRound: (values: any[]) => TimeScale; interpolate: { (): D3.Transition.Interpolate; @@ -2767,7 +2677,7 @@ declare module D3 { (range: D3.Time.Range, count: number): any[]; }; tickFormat(count: number): (n: number) => string; - copy(): TimeScale; + nice(count?: number): TimeScale; } } @@ -2932,19 +2842,19 @@ declare module D3 { /** * compute the latitude-longitude bounding box for a given feature. */ - bounds(feature: any): Array>; + bounds(feature: any): number[][]; /** * compute the spherical centroid of a given feature. */ - centroid(feature: any): Array; + centroid(feature: any): number[]; /** * compute the great-arc distance between two points. */ - distance(a: Array, b: Array): number; + distance(a: number[], b: number[]): number; /** * interpolate between two points along a great arc. */ - interpolate(a: Array, b: Array): (t: number) => Array; + interpolate(a: number[], b: number[]): (t: number) => number[]; /** * compute the length of a line string or the circumference of a polygon. */ @@ -3057,7 +2967,7 @@ declare module D3 { /** * */ - rotation(rotation: Array): Rotation; + rotation(rotation: number[]): Rotation; } export interface Path { @@ -3131,11 +3041,11 @@ declare module D3 { } export interface Circle { - (...args: Array): GeoJSON; + (...args: any[]): GeoJSON; origin: { - (): Array; - (origin: Array): Circle; - (origin: (...args: Array) => Array): Circle; + (): number[]; + (origin: number[]): Circle; + (origin: (...args: any[]) => number[]): Circle; } angle: { (): number; @@ -3149,31 +3059,31 @@ declare module D3 { export interface Graticule{ (): GeoJSON; - lines(): Array; + lines(): GeoJSON[]; outline(): GeoJSON; extent: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } minorExtent: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } majorExtent: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } step: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } minorStep: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } majorStep: { - (): Array>; - (extent: Array>): Graticule; + (): number[][]; + (extent: number[][]): Graticule; } precision: { (): number; @@ -3199,33 +3109,33 @@ declare module D3 { } export interface GeoJSON { - coordinates: Array>; + coordinates: number[][]; type: string; } export interface RawProjection { - (lambda: number, phi: number): Array; - invert?(x: number, y: number): Array; + (lambda: number, phi: number): number[]; + invert?(x: number, y: number): number[]; } export interface Projection { - (coordinates: Array): Array; - invert?(point: Array): Array; + (coordinates: number[]): number[]; + invert?(point: number[]): number[]; rotate: { - (): Array; - (rotation: Array): Projection; + (): number[]; + (rotation: number[]): Projection; }; center: { - (): Array; - (location: Array): Projection; + (): number[]; + (location: number[]): Projection; }; parallels: { - (): Array; - (location: Array): Projection; + (): number[]; + (location: number[]): Projection; }; translate: { - (): Array; - (point: Array): Projection; + (): number[]; + (point: number[]): Projection; }; scale: { (): number; @@ -3236,8 +3146,8 @@ declare module D3 { (angle: number): Projection; }; clipExtent: { - (): Array>; - (extent: Array>): Projection; + (): number[][]; + (extent: number[][]): Projection; }; precision: { (): number; @@ -3256,8 +3166,8 @@ declare module D3 { } export interface Rotation extends Array { - (location: Array): Rotation; - invert(location: Array): Rotation; + (location: number[]): Rotation; + invert(location: number[]): Rotation; } export interface ProjectionMutator { @@ -3272,11 +3182,11 @@ declare module D3 { /** * compute the Voronoi diagram for the specified points. */ - voronoi(vertices: Array): Array; + voronoi(vertices: Vertice[]): Polygon[]; /** * compute the Delaunay triangulation for the specified points. */ - delaunay(vertices?: Array): Array; + delaunay(vertices?: Vertice[]): Polygon[]; /** * constructs a quadtree for an array of points. */ @@ -3284,21 +3194,21 @@ declare module D3 { /** * Constructs a new quadtree for the specified array of points. */ - quadtree(points: Array, x1: number, y1: number, x2: number, y2: number): Quadtree; + quadtree(points: Point[], x1: number, y1: number, x2: number, y2: number): Quadtree; /** * Constructs a new quadtree for the specified array of points. */ - quadtree(points: Array, width: number, height: number): Quadtree; + quadtree(points: Point[], width: number, height: number): Quadtree; /** * Returns the input array of vertices with additional methods attached */ - polygon(vertices:Array): Polygon; + polygon(vertices:Vertice[]): Polygon; /** * creates a new hull layout with the default settings. */ hull(): Hull; - hull(vertices:Array): Array; + hull(vertices:Vertice[]): Vertice[]; } export interface Vertice extends Array { @@ -3316,7 +3226,7 @@ declare module D3 { /** * Returns a two-element array representing the centroid of this polygon. */ - centroid(): Array; + centroid(): number[]; /** * Clips the subject polygon against this polygon */ @@ -3331,11 +3241,11 @@ declare module D3 { /** * Constructs a new quadtree for the specified array of points. */ - (points: Array, x1: number, y1: number, x2: number, y2: number): Quadtree; + (points: Point[], x1: number, y1: number, x2: number, y2: number): Quadtree; /** * Constructs a new quadtree for the specified array of points. */ - (points: Array, width: number, height: number): Quadtree; + (points: Point[], width: number, height: number): Quadtree; x: { (): (d: any) => any; @@ -3347,10 +3257,10 @@ declare module D3 { (accesor: (d: any) => any): QuadtreeFactory; } - size(): Array; - size(size: Array): QuadtreeFactory; - extent(): Array>; - extent(points: Array>): QuadtreeFactory; + size(): number[]; + size(size: number[]): QuadtreeFactory; + extent(): number[][]; + extent(points: number[][]): QuadtreeFactory; } export interface Quadtree { @@ -3370,15 +3280,15 @@ declare module D3 { /** * Compute the Voronoi diagram for the specified data. */ - (data: Array): Array; + (data: T[]): Polygon[]; /** * Compute the graph links for the Voronoi diagram for the specified data. */ - links(data: Array): Array; + links(data: T[]): Layout.GraphLink[]; /** * Compute the triangles for the Voronoi diagram for the specified data. */ - triangles(data: Array): Array>; + triangles(data: T[]): number[][]; x: { /** * Get the x-coordinate accessor. @@ -3417,36 +3327,36 @@ declare module D3 { * * @param constant The new constant value. */ - (constant: number): Voronoi; + (constant: number): Voronoi; } clipExtent: { /** * Get the clip extent. */ - (): Array>; + (): number[][]; /** * Set the clip extent. * * @param extent The new clip extent. */ - (extent: Array>): Voronoi; + (extent: number[][]): Voronoi; } size: { /** * Get the size. */ - (): Array; + (): number[]; /** * Set the size, equivalent to a clip extent starting from (0,0). * * @param size The new size. */ - (size: Array): Voronoi; + (size: number[]): Voronoi; } } export interface Hull { - (vertices: Array): Array; + (vertices: Vertice[]): Vertice[]; x: { (): (d: any) => any; (accesor: (d: any) => any): any; @@ -3460,3 +3370,7 @@ declare module D3 { } declare var d3: D3.Base; + +declare module "d3" { + export = d3; +} diff --git a/dropboxjs/dropboxjs-tests.ts b/dropboxjs/dropboxjs-tests.ts new file mode 100644 index 000000000..ad8e608a4 --- /dev/null +++ b/dropboxjs/dropboxjs-tests.ts @@ -0,0 +1,54 @@ +/// + +var browserClient = new Dropbox.Client({ key: "your-key-here" }); + +browserClient.authenticate((error:any, client:Dropbox.Client) => { + if (error) { + alert(error); + } + + client.onError.addListener((error:any) =>{ + if (window['console']) { // Skip the "if" in node.js code. + console.error(error); + } + }); + + client.getAccountInfo( (error:Dropbox.ApiError, accountInfo:Dropbox.AccountInfo) => { + if (error) { + alert(error); // Something went wrong. + } + + alert("Hello, " + accountInfo.name + "!"); + }); + + client.writeFile("hello_world.txt", "Hello, world!\n", (error:Dropbox.ApiError, stat:Dropbox.File.Stat ) => { + if (error) { + alert(error); // Something went wrong. + } + + alert("File saved as revision " + stat.versionTag); + }); + + client.readFile("hello_world.txt", (error:Dropbox.ApiError, data:string) => { + if (error) { + alert(error); // Something went wrong. + } + + alert(data); // data has the file's contents + }); + + client.readdir("/", (err: Dropbox.ApiError, filenames: string[], stat: Dropbox.File.Stat, folderEntries: Dropbox.File.Stat[]) => { + if (error) { + alert(error); // Something went wrong. + } + + alert("Your Dropbox contains " + filenames.join(", ")); + }); +}); + +var serverClient = new Dropbox.Client({ + key: "your-key-here", + secret: "your-secret-here" +}); + +serverClient.authDriver(new Dropbox.AuthDriver.NodeServer({port:8191})); \ No newline at end of file diff --git a/dropboxjs/dropboxjs.d.ts b/dropboxjs/dropboxjs.d.ts new file mode 100644 index 000000000..f9a2c9a40 --- /dev/null +++ b/dropboxjs/dropboxjs.d.ts @@ -0,0 +1,508 @@ +// Type definitions for dropbox-js +// Project: https://github.com/dropbox/dropbox-js +// Definitions by: Steve Fenton , Pedro Casaubon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module Dropbox { + + + interface QueryParams { + [key: string]: any; + } + interface Credentials { + key: string; + secret?: string; + token?: string; + uid?: string; + } + + + /* Callbacks */ + + interface AuthenticateCallback { + (err: ApiError, client: Client): void; + (err: AuthError, client: Client): void; + } + + interface QueryParamsCallback { + (queryParams: QueryParams): void; + } + + interface ClientFileReadCallback { + + (err: ApiError, fileContents: string, stat: File.Stat, rangeInfo: Http.RangeInfo): void; + } + + interface ClientFileWriteCallback { + + (err: ApiError, stat: File.Stat): void; + } + + interface ResumableUploadStepCallback { + (err: ApiError, uploadCursor: Http.UploadCursor): void; + } + + interface ReadThumbnailCallback { + (err: ApiError, imageData: string, stat: File.Stat): void; + (err: ApiError, imageData: Blob, stat: File.Stat): void; + } + + interface FileStatCallback { + (err: ApiError, stat: File.Stat): void; + } + + /* Options */ + + interface AuthenticateOptions { + interactive: boolean; + } + + interface SingOutOptions { + mustInvalidate: boolean; + } + + interface AccountInfoOptions { + httpCache: boolean; + } + + interface ClientFileReadOptions { + + versionTag?: string; + rev?: string; + arrayBuffer?: boolean; + blob?: boolean; + buffer?: boolean; + binary?: boolean; + length?: number; + start?: number; + httpCache?: boolean; + } + + interface ClientFileWriteOptions { + lastVersionTag?: string; + parentRev?: string; + noOverwrite?: boolean; + } + + interface ReadDirOptions { + removed?: boolean; + deleted?: boolean; + limit?: any; + versionTag?: string; + contentHash?: string; + httpCache?: boolean; + } + + interface MakeURLOptions { + download?: boolean; + downloadHack?: boolean; + long?: boolean; + longUrl?: boolean; + } + + interface HistoryOptions { + limit?: number; + httpCache?: boolean; + + } + + interface ThumbnailUrlOptions { + png?: boolean; + format?: string; + size?: string; + } + + interface ReadThumbnailOptions extends ThumbnailUrlOptions { + arrayBuffer?: boolean; + blob?: boolean; + buffer?: boolean; + } + + interface FindByNameOptions { + limit?: number; + removed?: boolean; + deleted?: boolean; + httpCache?: boolean; + + } + + interface RedirectOptions { + redirectUrl?: string; + redirectFile?: string; + scope?: string; + rememberUser?: boolean; + } + + module Util { + + class EventSource { + constructor(options: { cancelable: boolean }); + addListener(listener: (event: any) => void): EventSource; + removeListener(listener: (event: any) => void): EventSource; + dispatch(event: {}): boolean; + } + + class Oauth { + static queryParamsFromUrl(url: string): QueryParams; + static randomAuthStateParam(): string; + checkAuthStateParam(stateParam: string): boolean; + } + + class Xhr { + xhr: XMLHttpRequest; + onError: (error: ApiError, callBack: (error: ApiError) => void) => void; + + constructor(method: string, baseUrl: string); + static urlEncode(obj: {}): string; + static urlEncodeValue(obj: {}): string; + static urlDecode(string: {}): QueryParams; + + + setParams(params: QueryParams): Xhr; + setCallback(callback: (err: ApiError, responseType: string, metadataHeader: {}, headers: {}) => void): Xhr; + signWithOauth(oauth: Oauth, cacheFriendly: boolean): Xhr; + addOauthParams(oauth: Oauth): Xhr; + addOauthHeader(oauth: Oauth): Xhr; + + setBody(body: string): Xhr; + setBody(body: Blob): Xhr; + setBody(body: ArrayBuffer): Xhr; + + setResponseType(responseType: string): Xhr; + setHeader(headerName: string, value: string): Xhr; + reportResponseHeaders(): Xhr; + setFileField(fieldName: string, fileName: string, fileData: string, contentType?: string): void; + setFileField(fieldName: string, fileName: string, fileData: Blob, contentType?: string): void; + setFileField(fieldName: string, fileName: string, fileData: File, contentType?: string): void; + prepare(): Xhr; + send(callback: (err: ApiError, responseType: string, metadataHeader: {}) => void): Xhr; + onReadyStateChange(): void; + onXdrLoad(): void; + onXdrError(): void; + } + } + module Http { + class AppInfo { + static ICON_SMALL: number; + static ICON_LARGE: number; + static parse(appInfo: {}, appKey?: string): AppInfo; + name: string; + key: string; + canUseDatastores: boolean; + canUseFiles: boolean; + hasAppFolder: boolean; + canUseFullDropbox: boolean; + icon(width: number, height?: number): void; + } + + class PollResult { + static parse(response: {}): PollResult; + hasChanges: boolean; + retryAfter: number; + } + + class PulledChanges { + static parse(deltaInfo: {}): PulledChanges; + blankSlate: boolean; + cursorTag: string; + shouldPullAgain: boolean; + shouldBackOff: boolean; + cursor(): string; + } + + class PulledChange { + static parse(entry: {}): PulledChange; + path: string; + wasRemoved: boolean; + stat: File.Stat; + } + + class RangeInfo { + static parse(headerValue: string): RangeInfo; + start: number; + size: number; + end: number; + } + + class UploadCursor { + static parse(cursorData: string): UploadCursor; + static parse(cursorData: {}): UploadCursor; + constructor(cursorData: string); + constructor(cursorData: {}); + tag: string; + offset: number; + expiresAt: Date; + toJSON(): {}; + } + } + module File { + + interface StatOptions { + version: number; + removed: boolean; + deleted: boolean; + readDir: boolean; + versionTag: string; + rev: string; + contentHash: string; + hash: string; + httpCache: boolean; + } + + class ShareUrl { + static parse(urlData: string, isDirect: boolean): ShareUrl; + static parse(urlData: {}, isDirect: boolean): ShareUrl; + url: string; + expiresAt: Date; + isDirect: boolean; + isPreview: boolean; + toJSON(): {}; + } + + class CopyReference { + static parse(refData: string): CopyReference; + static parse(refData: {}): CopyReference; + tag: string; + expiresAt: Date; + toJSON(): {}; + } + + class Stat { + static parse(metadata: {}): Stat; + path: string; + name: string; + inAppFolder: boolean; + isFolder: boolean; + isFile: boolean; + isRemoved: boolean; + typeIcon: string; + versionTag: string; + contentHash: string; + mimeType: string; + size: number; + humanSize: string; + hasThumbnail: boolean; + modifiedAt: Date; + clientModifiedAt: Date; + toJSON(): {}; + } + } + module AuthDriver { + + /** Do not use class! TypeScript definition implementation detail : https://github.com/Microsoft/TypeScript/issues/371 */ + class IAuthDriver { + doAuthorize(authUrl: string, stateParam: string, client: Client, callback?: QueryParamsCallback): void; + } + + class BrowserBase { + static localStorage(): Storage; + static currentLocation(): string; + static cleanupLocation(): void; + + constructor(options: { scope: string; rememberUser: boolean }); + authType(): string; + onAuthStepChange(client: Client, callback: () => void): void; + locationStateParam(url: string): string; + } + + class Redirect { + constructor(options?: { redirectUrl: string; redirectFile: string; scope: string; rememberUser: boolean }); + url(): string; + doAuthorize(authUrl: string, stateParam: string, client: Client): void; + resumeAuthorize(stateParam: string, client: Client, callback: QueryParamsCallback): void; + + } + + class Popup extends IAuthDriver { + static locationOrigin(location: string): string; + static oauthReceiver(): void; + constructor(options?: RedirectOptions); + url(): string; + + } + + class ChromeApp extends IAuthDriver { + constructor(options?: { scope: string }); + } + + class ChromeExtension extends IAuthDriver { + static oauthReceiver(): void; + constructor(options?: { scope: string; receiverPath: string }); + } + + class Cordova extends IAuthDriver { + static oauthReceiver(): void; + constructor(options?: { scope: string; receiverPath: string }); + url(): string; + } + + class NodeServer extends IAuthDriver { + constructor(options?: { port: number; tls?: {} }); + authType(): string; + url(): string; + openBrowser(url: string): void; + createApp(): void; + closeServer(): void; + + // TODO check request response types + doRequest(request:any, response:any): void; + closeBrowser(response:any): void; + } + } + + + class AuthDriver { + authType(): string; + url(): string; + doAuthorize(authUrl: string, stateParam: string, client: Client, callback: QueryParamsCallback): void; + getStateParam(client: Client, callback: (state: string) => void): void; + resumeAuthorize(stateParam: string, client: Client, callback: QueryParamsCallback): void; + onAuthStepChange(client: Client, callback: () => void): void; + } + + class AccountInfo { + static parse(acountInfo: {}): AccountInfo; + name: string; + email: string; + countryCode: string; + uid: string; + referralUrl: string; + publicAppUrl: string; + quota: number; + usedQuota: number; + privateBytes: number; + sharedBytes: number; + json(): {}; + } + + class ApiError { + status: number; + method: string; + url: string; + responseText: string; + response: {}; + + constructor(xhr: XMLHttpRequest, method: string, url: string); + + static NETWORK_ERROR: number; + static NO_CONTENT: number; + static INVALID_PARAM: number; + static INVALID_TOKEN: number; + static OAUTH_ERROR: number; + static NOT_FOUND: number; + static INVALID_METHOD: number; + static NOT_ACCEPTABLE: number; + static CONFLICT: number; + static RATE_LIMITED: number; + static SERVER_ERROR: number; + static OVER_QUOTA: number; + } + + class AuthError { + + code: string; + description: string; + uri: string; + constructor(queryString: QueryParams); + + static ACCESS_DENIED: string; + static INVALID_REQUEST: string; + static UNAUTHORIZED_CLIENT: string; + static INVALID_GRANT: string; + static INVALID_SCOPE: string; + static UNSUPPORTED_GRANT_TYPE: string; + static UNSUPPORTED_RESPONSE_TYPE: string; + static SERVER_ERROR: string; + static TEMPORARILY_UNAVAILABLE: string; + } + + class Client { + static ERROR: number; + static RESET: number; + static PARAM_SET: number; + static PARAM_LOADED: number; + static AUTHORIZED: number; + static DONE: number; + static SIGNED_OUT: number; + + onXhr: Util.EventSource; + onError: Util.EventSource; + onAuthStepChange: Util.EventSource; + authStep: number; + + constructor(options: Credentials); + authDriver(driver: AuthDriver.IAuthDriver): Client; + dropboxUid(): string; + credentials(): Credentials; + + // TODO check the error interface + authenticate(): Client; + authenticate(callback: AuthenticateCallback): Client; + authenticate(options: AuthenticateOptions): Client; + authenticate(options: AuthenticateOptions, callback: AuthenticateCallback): Client; + isAuthenticated(): boolean; + signOut(callback: (err: ApiError) => void): XMLHttpRequest; + signOut(options: SingOutOptions, callback: (err: ApiError) => void): XMLHttpRequest; + signOff(callback: (err: ApiError) => void): void; + signOff(options: SingOutOptions, callback: (err: ApiError) => void): void; + getAccountInfo(callback: (err: ApiError, accountInfo: AccountInfo, AccountInfo: AccountInfo) => void): XMLHttpRequest; + getAccountInfo(options: AccountInfoOptions, callback: (err: ApiError, accountInfo: AccountInfo, AccountInfo: AccountInfo) => void): XMLHttpRequest; + readFile(path: string, callback: ClientFileReadCallback): XMLHttpRequest; + readFile(path: string, options: ClientFileReadOptions, callback: ClientFileReadCallback): XMLHttpRequest; + writeFile(path: string, data: any, callback: ClientFileWriteCallback): XMLHttpRequest; + writeFile(path: string, data: any, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; + resumableUploadStep(data: any, callback: ResumableUploadStepCallback): XMLHttpRequest; + resumableUploadStep(data: any, cursor: Http.UploadCursor, callback: ResumableUploadStepCallback): XMLHttpRequest; + resumableUploadFinish(path: string, cursor: Http.UploadCursor, callback: ClientFileWriteCallback): XMLHttpRequest; + resumableUploadFinish(path: string, cursor: Http.UploadCursor, options: ClientFileWriteOptions, callback: ClientFileWriteCallback): XMLHttpRequest; + stat(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + stat(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + readdir(path: string, options: ReadDirOptions, callback: (err: ApiError, filenames: string[], stat: File.Stat, folderEntries: File.Stat[]) => void): XMLHttpRequest; + metadata(path: string, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): void; + metadata(path: string, options: File.StatOptions, callback: (err: ApiError, stat: File.Stat, folderEntries: File.Stat[]) => void): void; + makeUrl(path: string, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; + makeUrl(path: string, options: MakeURLOptions, callback: (err: ApiError, shareUrl: File.ShareUrl) => void): XMLHttpRequest; + history(path: string, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; + history(path: string, options: HistoryOptions, callback: (err: ApiError, fileVersions: File.Stat[]) => void): XMLHttpRequest; + revisions(path: string, options: HistoryOptions, callback: (err: ApiError, fileVersions: File.Stat[]) => void): void; + thumbnailUrl(path: string, options?: ThumbnailUrlOptions): string; + readThumbnail(path: string, callback: ReadThumbnailCallback): XMLHttpRequest; + readThumbnail(path: string, options: ReadThumbnailOptions, callback: ReadThumbnailCallback): XMLHttpRequest; + revertFile(path: string, versionTag: string, callback: FileStatCallback): XMLHttpRequest; + restore(path: string, versionTag: string, callback: FileStatCallback): void; + findByName(path: string, namePattern: string, callback: (err: ApiError, resultStats: File.Stat[]) => void): XMLHttpRequest; + findByName(path: string, namePattern: string, options: FindByNameOptions, callback: (err: ApiError, resultStats: File.Stat[]) => void): XMLHttpRequest; + search(path: string, namePattern: string, options: FindByNameOptions, callback: (err: ApiError, resultStats: File.Stat[]) => void): void; + makeCopyReference(path: string, callback: (err: ApiError, copyReference: File.CopyReference) => void): XMLHttpRequest; + copyRef(path: string, callback: (err: ApiError, copyReference: File.CopyReference) => void): XMLHttpRequest; + pullChanges(callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + pullChanges(cursor: string, callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + pullChanges(cursor: Http.PulledChanges, callback: (err: ApiError, changes: Http.PulledChanges) => void): XMLHttpRequest; + delta(cursor: string, callback: (err: ApiError, changes: Http.PulledChanges) => void): void; + delta(cursor: Http.PulledChanges, callback: (err: ApiError, changes: Http.PulledChanges) => void): void; + pollForChanges(cursor: string, options: {}, callback: (err: ApiError, changes: Http.PollResult) => void): void; + pollForChanges(cursor: Http.PulledChanges, options: {}, callback: (err: ApiError, changes: Http.PollResult) => void): void; + mkdir(path: string, callback: FileStatCallback): XMLHttpRequest; + remove(path: string, callback: FileStatCallback): XMLHttpRequest; + unlink(path: string, callback: FileStatCallback): void; + delete(path: string, callback: FileStatCallback): void; + copy(from: string, toPath: string, callback: FileStatCallback): XMLHttpRequest; + copy(from: File.CopyReference, toPath: string, callback: FileStatCallback): XMLHttpRequest; + move(fromPath: string, toPath: string, callback: FileStatCallback): XMLHttpRequest; + appInfo(callback: (err: ApiError, changes: Http.AppInfo) => void): XMLHttpRequest; + appInfo(appKey: string, callback: (err: ApiError, changes: Http.AppInfo) => void): XMLHttpRequest; + + // TODO check if this can better be described + isAppDeveloper(userId:any, callbackcallback: (err: ApiError, isAppDeveloper: boolean) => void): XMLHttpRequest; + isAppDeveloper(userId:any, appKey:any, callbackcallback: (err: ApiError, isAppDeveloper: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, appKey: string, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + hasOauthRedirectUri(redirectUri: string, appKey: Http.AppInfo, callback: (err: ApiError, hasOauthRedirectUri: boolean) => void): XMLHttpRequest; + reset(): Client; + setCredentials(credentials: Credentials): Client; + appHash(): string; + + } +} diff --git a/ember/ember.d.ts b/ember/ember.d.ts index bbb555e8a..2a0b35e42 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -2235,7 +2235,6 @@ declare module Em { var print: typeof Ember.Handlebars.print; var logger: typeof Ember.Handlebars.logger; var log: typeof Ember.Handlebars.log; - var compile: typeof Ember.Handlebars.compile; } class HashLocation extends Ember.HashLocation { } class HistoryLocation extends Ember.HistoryLocation { } diff --git a/errorhandler/errorhandler-tests.ts b/errorhandler/errorhandler-tests.ts new file mode 100644 index 000000000..1d02ed14c --- /dev/null +++ b/errorhandler/errorhandler-tests.ts @@ -0,0 +1,7 @@ +/// + +import express = require('express'); +import errorhandler = require('errorhandler'); +var app = express(); + +app.use(errorhandler()); diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts new file mode 100644 index 000000000..31bf44ce1 --- /dev/null +++ b/errorhandler/errorhandler.d.ts @@ -0,0 +1,12 @@ +// Type definitions for errorhandler +// Project: https://github.com/expressjs/errorhandler +// Definitions by: Santi Albo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "errorhandler" { + import express = require('express'); + function e(): express.ErrorRequestHandler; + export = e; +} \ No newline at end of file diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index b18b17e96..5a5df2fa0 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,161 +1,173 @@ // Type definitions for express-validator // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley +// Definitions by: Nathan Ridley , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module ExpressValidator { - export interface ValidationError { - msg: string; - param: string; - } +/// - export interface RequestValidation { - check(field: string, message: string): Validator; - assert(field: string, message: string): Validator; - sanitize(field: string): Sanitizer; - onValidationError(func: (msg: string) => void): void; - } - - export interface Validator { - /** - * Alias for regex() - */ - is(): Validator; - /** - * Alias for notRegex() - */ - not(): Validator; - isEmail(): Validator; - /** - * Accepts http, https, ftp - */ - isUrl(): Validator; - /** - * Combines isIPv4 and isIPv6 - */ - isIP(): Validator; - isIPv4(): Validator; - isIPv6(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; - isNumeric(): Validator; - isHexadecimal(): Validator; - /** - * Accepts valid hexcolors with or without # prefix - */ - isHexColor(): Validator; - /** - * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't - */ - isInt(): Validator; - isLowercase(): Validator; - isUppercase(): Validator; - isDecimal(): Validator; - /** - * Alias for isDecimal - */ - isFloat(): Validator; - /** - * Check if length is 0 - */ - notNull(): Validator; - isNull(): Validator; - /** - * Not just whitespace (input.trim().length !== 0) - */ - notEmpty(): Validator; - equals(equals: any): Validator; - contains(str: string): Validator; - notContains(str: string): Validator; - /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') - */ - regex(pattern: string, modifiers: string): Validator; - notRegex(pattern: string, modifiers: string): Validator; - /** - * max is optional - */ - len(min: number, max?: number): Validator; - /** - * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier - */ - isUUID(version: number): Validator; - /** - * Alias for isUUID(3) - */ - isUUIDv3(): Validator; - /** - * Alias for isUUID(4) - */ - isUUIDv4(): Validator; - /** - * Alias for isUUID(5) - */ - isUUIDv5(): Validator; - /** - * Uses Date.parse() - regex is probably a better choice - */ - isDate(): Validator; - /** - * Argument is optional and defaults to today. Comparison is non-inclusive - */ - isAfter(date: Date): Validator; - /** - * Argument is optional and defaults to today. Comparison is non-inclusive - */ - isBefore(date: Date): Validator; - isIn(options: string): Validator; - isIn(options: string[]): Validator; - notIn(options: string): Validator; - notIn(options: string[]): Validator; - max(val: string): Validator; - min(val: string): Validator; - /** - * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats - */ - isCreditCard(): Validator; - } - - interface Sanitizer { - /** - * Trim optional `chars`, default is to trim whitespace (\r\n\t ) - */ - trim(...chars: string[]): Sanitizer; - ltrim(...chars: string[]): Sanitizer; - rtrim(...chars: string[]): Sanitizer; - ifNull(replace: any): Sanitizer; - toFloat(): Sanitizer; - toInt(): Sanitizer; - /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities - */ - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; - /** - * Escape &, <, >, and " - */ - escape(): Sanitizer; - /** - * Remove common XSS attack vectors from user-supplied HTML - */ - xss(): Sanitizer; - /** - * Remove common XSS attack vectors from images - */ - xss(fromImages: boolean): Sanitizer; - } -} - -declare function ExpressValidator(): void; declare module "express-validator" { - export = ExpressValidator; + import express = require('express'); + + module ExpressValidator { + + export interface ValidationError { + msg: string; + param: string; + } + + export interface RequestValidation { + check(field:string, message:string): Validator; + assert(field:string, message:string): Validator; + sanitize(field:string): Sanitizer; + onValidationError(func:(msg:string) => void): void; + validationErrors() : any; + } + + export interface Validator { + /** + * Alias for regex() + */ + is(): Validator; + /** + * Alias for notRegex() + */ + not(): Validator; + isEmail(): Validator; + /** + * Accepts http, https, ftp + */ + isUrl(): Validator; + /** + * Combines isIPv4 and isIPv6 + */ + isIP(): Validator; + isIPv4(): Validator; + isIPv6(): Validator; + isAlpha(): Validator; + isAlphanumeric(): Validator; + isNumeric(): Validator; + isHexadecimal(): Validator; + /** + * Accepts valid hexcolors with or without # prefix + */ + isHexColor(): Validator; + /** + * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't + */ + isInt(): Validator; + isLowercase(): Validator; + isUppercase(): Validator; + isDecimal(): Validator; + /** + * Alias for isDecimal + */ + isFloat(): Validator; + /** + * Check if length is 0 + */ + notNull(): Validator; + isNull(): Validator; + /** + * Not just whitespace (input.trim().length !== 0) + */ + notEmpty(): Validator; + equals(equals:any): Validator; + contains(str:string): Validator; + notContains(str:string): Validator; + /** + * Usage: regex(/[a-z]/i) or regex('[a-z]','i') + */ + regex(pattern:string, modifiers:string): Validator; + notRegex(pattern:string, modifiers:string): Validator; + /** + * max is optional + */ + len(min:number, max?:number): Validator; + /** + * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier + */ + isUUID(version:number): Validator; + /** + * Alias for isUUID(3) + */ + isUUIDv3(): Validator; + /** + * Alias for isUUID(4) + */ + isUUIDv4(): Validator; + /** + * Alias for isUUID(5) + */ + isUUIDv5(): Validator; + /** + * Uses Date.parse() - regex is probably a better choice + */ + isDate(): Validator; + /** + * Argument is optional and defaults to today. Comparison is non-inclusive + */ + isAfter(date:Date): Validator; + /** + * Argument is optional and defaults to today. Comparison is non-inclusive + */ + isBefore(date:Date): Validator; + isIn(options:string): Validator; + isIn(options:string[]): Validator; + notIn(options:string): Validator; + notIn(options:string[]): Validator; + max(val:string): Validator; + min(val:string): Validator; + /** + * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats + */ + isCreditCard(): Validator; + } + + interface Sanitizer { + /** + * Trim optional `chars`, default is to trim whitespace (\r\n\t ) + */ + trim(...chars:string[]): Sanitizer; + ltrim(...chars:string[]): Sanitizer; + rtrim(...chars:string[]): Sanitizer; + ifNull(replace:any): Sanitizer; + toFloat(): Sanitizer; + toInt(): Sanitizer; + /** + * True unless str = '0', 'false', or str.length == 0 + */ + toBoolean(): Sanitizer; + /** + * False unless str = '1' or 'true' + */ + toBooleanStrict(): Sanitizer; + /** + * Decode HTML entities + */ + entityDecode(): Sanitizer; + entityEncode(): Sanitizer; + /** + * Escape &, <, >, and " + */ + escape(): Sanitizer; + /** + * Remove common XSS attack vectors from user-supplied HTML + */ + xss(): Sanitizer; + /** + * Remove common XSS attack vectors from images + */ + xss(fromImages:boolean): Sanitizer; + } + } + + /** + * + * @middlewareOptions see: https://github.com/ctavan/express-validator#middleware-options + */ + function ExpressValidator(middlewareOptions?:any):express.RequestHandler; + + + export = ExpressValidator; } diff --git a/express/express-tests.ts b/express/express-tests.ts index 57d1d638c..76fa4da0d 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -3,1496 +3,34 @@ import express = require('express'); var app = express(); -////////////////////////// +app.engine('jade', require('jade').__express); +app.engine('html', require('ejs').renderFile); -var hash: any; - -// config - -app.set('view engine', 'ejs'); -app.set('views', __dirname + '/views'); - -// middleware - -app.use(express.bodyParser()); -app.use(express.cookieParser('shhhh, very secret')); -app.use(express.session()); - -// Session-persisted message middleware - -app.use((req: express.Request, res: express.Response, next) => { - var err = req.session.error - , msg = req.session.success; - delete req.session.error; - delete req.session.success; - res.locals.message = ''; - if (err) res.locals.message = '

' + err + '

'; - if (msg) res.locals.message = '

' + msg + '

'; - next(); -}); - -// dummy database - -var users = { - tj: { name: 'tj' } -}; - -// when you create a user, generate a salt -// and hash the password ('foobar' is the pass here) - -hash('foobar', (err, salt, hash) => { - if (err) throw err; - // store the salt & hash in the "db" - users.tj.salt = salt; - users.tj.hash = hash; -}); - - -// Authenticate using our plain-object database of doom! - -function authenticate(name, pass, fn) { - if (!module.parent) console.log('authenticating %s:%s', name, pass); - var user = users[name]; - // query the db for the given username - if (!user) return fn(new Error('cannot find user')); - // apply the same algorithm to the POSTed password, applying - // the hash against the pass / salt, if there is a match we - // found the user - hash(pass, user.salt, (err, hash) => { - if (err) return fn(err); - if (hash == user.hash) return fn(null, user); - fn(new Error('invalid password')); - }); -} - -function restrict(req: express.Request, res: express.Response, next?: Function) { - if (req.session.user) { - next(); - } else { - req.session.error = 'Access denied!'; - res.redirect('/login'); - } -} - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('login'); -}); - -app.get('/restricted', restrict, (req: express.Request, res: express.Response) => { - res.send('Wahoo! restricted area, click to logout'); -}); - -app.get('/logout', (req: express.Request, res: express.Response) => { - // destroy the user's session to log them out - // will be re-created next request - req.session.destroy(() => { - res.redirect('/'); - }); -}); - -app.get('/login', (req: express.Request, res: express.Response) => { - res.render('login'); -}); - -app.post('/login', (req: express.Request, res: express.Response) => { - authenticate(req.body.username, req.body.password, (err, user) => { - if (user) { - // Regenerate session when signing in - // to prevent fixation - req.session.regenerate(() => { - // Store the user's primary key - // in the session store to be retrieved, - // or in this case the entire user object - req.session.user = user; - req.session.success = 'Authenticated as ' + user.name - + ' click to logout. ' - + ' You may now access /restricted.'; - res.redirect('back'); - }); - } else { - req.session.error = 'Authentication failed, please check your ' - + ' username and password.' - + ' (use "tj" and "foobar")'; - res.redirect('login'); - } - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////// - -app.set('views', __dirname); -app.set('view engine', 'jade'); - -var pets = []; - -var n = 1000; -while (n--) { - pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); - pets.push({ name: 'Loki', age: 1, species: 'ferret' }); - pets.push({ name: 'Jane', age: 6, species: 'ferret' }); -} - -app.use(express.logger('dev')); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('pets', { pets: pets }); -}); - -app.listen(3000); -console.log('Express listening on port 3000'); - -///////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.format({ - html: () => { - res.send('
    ' + users.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('') + '
'); - }, - - text: () => { - res.send(users.map(user => { - return ' - ' + user.name + '\n'; - }).join('')); - }, - - json: () => { - res.json(users); - } - }); -}); - -// or you could write a tiny middleware like -// this to abstract make things a bit more declarative: - -function format(mod) { - var obj = require(mod); - return (req: express.Request, res: express.Response) => { - res.format(obj); - }; -} - -app.get('/users', format('./users')); - -if (!module.parent) { - app.listen(3000); - console.log('listening on port 3000'); -} - -///////////////////////// - -// add favicon() before logger() so -// GET /favicon.ico requests are not -// logged, because this middleware -// reponds to /favicon.ico and does not -// call next() -app.use(express.favicon()); - -// custom log format -if ('test' != process.env.NODE_ENV) - app.use(express.logger(':method :url')); - -// parses request cookies, populating -// req.cookies and req.signedCookies -// when the secret is passed, used -// for signing the cookies. -app.use(express.cookieParser('my secret here')); - -// parses json, x-www-form-urlencoded, and multipart/form-data -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - if (req.cookies.remember) { - res.send('Remembered :). Click to forget!.'); - } else { - res.send('

Check to ' - + '.

'); - } -}); - -app.get('/forget', (req: express.Request, res: express.Response) => { - res.clearCookie('remember'); - res.redirect('back'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - var minute = 60000; - if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); - res.redirect('back'); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// ignore GET /favicon.ico -app.use(express.favicon()); - -// pass a secret to cookieParser() for signed cookies -app.use(express.cookieParser('manny is cool')); - -// add req.session cookie support -app.use(express.cookieSession()); - -// do something with the session -app.use(count); - -// custom middleware -function count(req: express.Request, res: express.Response) { - req.session.count = req.session.count || 0; - var n = req.session.count++; - res.send('viewed ' + n + ' times\n'); -} - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -/////////////// - -var api = app; - -app.use(express.static(__dirname + '/public')); - -// api middleware - -api.use(express.logger('dev')); -api.use(express.bodyParser()); - -/** - * CORS support. - */ - -api.all('*', (req: express.Request, res: express.Response, next) => { - if (!req.get('Origin')) return next(); - // use "*" here to accept any origin - res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); - res.set('Access-Control-Allow-Methods', 'GET, POST'); - res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); - // res.set('Access-Control-Allow-Max-Age', 3600); - if ('OPTIONS' == req.method) return res.send(200); - next(); -}); - -/** - * POST a user. - */ - -api.post('/user', (req: express.Request, res: express.Response) => { - console.log(req.body); - res.send(201); -}); - -app.listen(3000); -api.listen(3001); - -console.log('app listening on 3000'); -console.log('api listening on 3001'); - -//////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send(''); -}); - -// /files/* is accessed via req.params[0] -// but here we name it :file -app.get('/files/:file(*)', (req: express.Request, res: express.Response) => { - var file = req.params.file - , path = __dirname + '/files/' + file; - - res.download(path); -}); - -// error handling middleware. Because it's -// below our routes, you will be able to -// "intercept" errors, otherwise Connect -// will respond with 500 "Internal Server Error". -app.use((err, req, res: express.Response, next) => { - // special-case 404s, - // remember you could - // render a 404 template here - if (404 == err.status) { - res.statusCode = 404; - res.send('Cant find that file, sorry!'); - } else { - next(err); - } -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////// - -// Register ejs as .html. If we did -// not call this, we would need to -// name our views foo.ejs instead -// of foo.html. The __express method -// is simply a function that engines -// use to hook into the Express view -// system by default, so if we want -// to change "foo.ejs" to "foo.html" -// we simply pass _any_ function, in this -// case `ejs.__express`. - -app.engine('.html', require('ejs').__express); - -// Optional since express defaults to CWD/views - -app.set('views', __dirname + '/views'); - -// Without this you would need to -// supply the extension to res.render() -// ex: res.render('users.html'). -app.set('view engine', 'html'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('users', { - users: users, - title: "EJS example", - header: "Some users" - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express app started on port 3000'); -} - -//////////////////// - -var test: any; - -if (!test) app.use(express.logger('dev')); -app.use(app.router); - -// the error handler is strategically -// placed *below* the app.router; if it -// were above it would not receive errors -// from app.get() etc -app.use(error); - -// error handling middleware have an arity of 4 -// instead of the typical (req: express.Request, res: express.Response, next), -// otherwise they behave exactly like regular -// middleware, you may have several of them, -// in different orders etc. - -function error(err, req, res: express.Response, next) { - // log it - if (!test) console.error(err.stack); - - // respond with 500 "Internal Server Error". - res.send(500); -} - -app.get('/', () => { - // Caught and passed down to the errorHandler middleware - throw new Error('something broke!'); -}); - -app.get('/next', (req: express.Request, res: express.Response, next) => { - // We can also pass exceptions to next() - process.nextTick(() => { - next(new Error('oh no!')); - }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - -var silent: any; - -// general config -app.set('views', __dirname + '/views'); -app.set('view engine', 'jade'); - -// our custom "verbose errors" setting -// which we can use in the templates -// via settings['verbose errors'] -app.enable('verbose errors'); - -// disable them in production -// use $ NODE_ENV=production node examples/error-pages -if ('production' == app.settings.env) { - app.disable('verbose errors'); -} - -app.use(express.favicon()); - -silent || app.use(express.logger('dev')); - -// "app.router" positions our routes -// above the middleware defined below, -// this means that Express will attempt -// to match & call routes _before_ continuing -// on, at which point we assume it's a 404 because -// no route has handled the request. - -app.use(app.router); - -// Since this is the last non-error-handling -// middleware use()d, we assume 404, as nothing else -// responded. - -// $ curl http://localhost:3000/notfound -// $ curl http://localhost:3000/notfound -H "Accept: application/json" -// $ curl http://localhost:3000/notfound -H "Accept: text/plain" - -app.use((req: express.Request, res: express.Response) => { - res.status(404); - - // respond with html page - if (req.accepts('html')) { - res.render('404', { url: req.url }); - return; - } - - // respond with json - if (req.accepts('json')) { - res.send({ error: 'Not found' }); - return; - } - - // default to plain-text. send() - res.type('txt').send('Not found'); -}); - -// error-handling middleware, take the same form -// as regular middleware, however they require an -// arity of 4, aka the signature (err, req, res: express.Response, next). -// when connect has an error, it will invoke ONLY error-handling -// middleware. - -// If we were to next() here any remaining non-error-handling -// middleware would then be executed, or if we next(err) to -// continue passing the error, only error-handling middleware -// would remain being executed, however here -// we simply respond with an error page. - -app.use((err, req, res: express.Response) => { - // we may use properties of the error object - // here and next(err) appropriately, or if - // we possibly recovered from the error, simply next(). - res.status(err.status || 500); - res.render('500', { error: err }); -}); - -// Routes - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index.jade'); -}); - -app.get('/404', (req: express.Request, res: express.Response, next) => { - // trigger a 404 since no other middleware - // will match /404 after this one, and we're not - // responding here - next(); -}); - -app.get('/403', (req: express.Request, res: express.Response, next) => { - // trigger a 403 error - var err = new Error('not allowed!'); - err.status = 403; - next(err); -}); - -app.get('/500', (req: express.Request, res: express.Response, next) => { - // trigger a generic (500) error - next(new Error('keyboard cat!')); -}); - -if (!module.parent) { - app.listen(3000); - //silent ||  console.log('Express started on port 3000'); -} - -/////////////// - -var fs: any; -var md: any; - -app.set('view engine', 'jade'); -app.set('views', __dirname + '/views'); - -function User(name) { - this.private = 'heyyyy'; - this.secret = 'something'; - this.name = name; - this.id = 123; -} - -// You'll probably want to do -// something like this so you -// dont expose "secret" data. - -User.prototype.toJSON = function () { - return { - id: this.id, - name: this.name - }; -}; - -app.use(express.logger('dev')); - -// earlier on expose an object -// that we can tack properties on. -// all res.locals props are exposed -// to the templates, so "expose" will -// be present. - -app.use((req: express.Request, res: express.Response, next) => { - res.locals.expose = {}; - // you could alias this as req or res.expose - // to make it shorter and less annoying - next(); -}); - -// pretend we loaded a user - -app.use((req: express.Request, res: express.Response, next) => { - req.user = new User('Tobi'); - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user'); -}); - -app.get('/user', (req: express.Request, res: express.Response) => { - // we only want to expose the user - // to the client for this route: - res.locals.expose.user = req.user; - res.render('page'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////////// - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello World'); -}); - -app.listen(3000); -console.log('Express started on port 3000'); - -//////////////////// - -// register .md as an engine in express view system - -app.engine('md', (path, options, fn) => { - fs.readFile(path, 'utf8', (err, str) => { - if (err) return fn(err); - try { - var html = md(str); - html = html.replace(/\{([^}]+)\}/g, (_, name) => { - return options[name] || ''; - }); - fn(null, html); - } catch (err) { - fn(err); - } - }); -}); - -app.set('views', __dirname + '/views'); - -// make it the default so we dont need .md -app.set('view engine', 'md'); - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('index', { title: 'Markdown Example' }); -}); - -app.get('/fail', (req: express.Request, res: express.Response) => { - res.render('missing', { title: 'Markdown Example' }); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -/////////////////////// - -var mformat: any; - -// bodyParser in connect 2.x uses node-formidable to parse -// the multipart form data. -app.use(express.bodyParser()); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('
' - + '

Title:

' - + '

Image:

' - + '

' - + '
'); -}); - -app.post('/', (req: express.Request, res: express.Response) => { - // the uploaded file can be found as `req.files.image` and the - // title field as `req.body.title` - res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' - , req.files.image.name - , req.files.image.size / 1024 | 0 - , req.files.image.path - , req.body.title)); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - - -// first: -// $ npm install redis online -// $ redis-server - -/** - * Module dependencies. - */ - -var online: any; -var db: any; - -// online - -online = online(db); - -// activity tracking, in this case using -// the UA string, you would use req.user.id etc - -app.use((req: express.Request, res: express.Response, next) => { - // fire-and-forget - online.add(req.headers['user-agent']); - next(); -}); - -/** - * List helper. - */ - -function list(ids) { - return '
    ' + ids.map(id => { - return '
  • ' + id + '
  • '; - }).join('') + '
'; -} - -/** - * GET users online. - */ - -app.get('/', (req: express.Request, res: express.Response, next) => { - online.last(5, (err, ids) => { - if (err) return next(err); - res.send('

Users online: ' + ids.length + '

' + list(ids)); - }); -}); - -app.listen(3000); -console.log('listening on port 3000'); - -/////////////////// - -// Convert :to and :from to integers - -app.param(['to', 'from'], (req: express.Request, res: express.Response, next, num, name) => { - req.params[name] = num = parseInt(num, 10); - if (isNaN(num)) { - next(new Error('failed to parseInt ' + num)); - } else { - next(); - } -}); - -// Load user by id - -app.param('user', (req: express.Request, res: express.Response, next, id) => { - if (req.user = users[id]) { - next(); - } else { - next(new Error('failed to find user')); - } -}); - -/** - * GET index. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.send('Visit /user/0 or /users/0-2'); -}); - -/** - * GET :user. - */ - -app.get('/user/:user', (req: express.Request, res: express.Response) => { - res.send('user ' + req.user.name); -}); - -/** - * GET users :from - :to. - */ - -app.get('/users/:from-:to', (req: express.Request, res: express.Response) => { - var from = req.params.from - , to = req.params.to - , names = users.map(user => { return user.name; }); - res.send('users ' + names.slice(from, to).join(', ')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -////////////////// - -// Ad-hoc example resource method - -app.resource = function (path, obj) { - this.get(path, obj.index); - this.get(path + '/:a..:b.:format?', (req: express.Request, res: express.Response) => { - var a = parseInt(req.params.a, 10) - , b = parseInt(req.params.b, 10) - , format = req.params.format; - obj.range(req, res, a, b, format); - }); - this.get(path + '/:id', obj.show); - this.del(path + '/:id', obj.destroy); -}; - -// Fake controller. - -var FUser = { - index: (req: express.Request, res: express.Response) => { - res.send(users); - }, - show: (req: express.Request, res: express.Response) => { - res.send(users[req.params.id] || { error: 'Cannot find user' }); - }, - destroy: (req: express.Request, res: express.Response) => { - var id = req.params.id; - var destroyed = id in users; - delete users[id]; - res.send(destroyed ? 'destroyed' : 'Cannot find user'); - }, - range: (req: express.Request, res: express.Response, a, b, format) => { - var range = users.slice(a, b + 1); - switch (format) { - case 'json': - res.send(range); - break; - case 'html': - default: - var html = '
    ' + range.map(user => { - return '
  • ' + user.name + '
  • '; - }).join('\n') + '
'; - res.send(html); - break; - } - } -}; - -// curl http://localhost:3000/users -- responds with all users -// curl http://localhost:3000/users/1 -- responds with user 1 -// curl http://localhost:3000/users/4 -- responds with error -// curl http://localhost:3000/users/1..3 -- responds with several users -// curl -X DELETE http://localhost:3000/users/1 -- deletes the user - -app.resource('/users', FUser); - -app.get('/', (req: express.Request, res: express.Response) => { - res.send([ - '

Examples:

    ' - , '
  • GET /users
  • ' - , '
  • GET /users/1
  • ' - , '
  • GET /users/3
  • ' - , '
  • GET /users/1..3
  • ' - , '
  • GET /users/1..3.json
  • ' - , '
  • DELETE /users/4
  • ' - , '
' - ].join('\n')); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express started on port 3000'); -} - -///////////////////// - - -var verbose: any; - -app.map = (a, route) => { - route = route || ''; - for (var key in a) { - switch (typeof a[key]) { - // { '/path': { ... }} - case 'object': - app.map(a[key], route + key); - break; - // get: function(){ ... } - case 'function': - if (verbose) console.log('%s %s', key, route); - app[key](route, a[key]); - break; - } - } -}; - -var users2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user list'); - }, - - get: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete users'); - } -}; - -var pets2 = { - list: (req: express.Request, res: express.Response) => { - res.send('user ' + req.params.uid + '\'s pets'); - }, - - del: (req: express.Request, res: express.Response) => { - res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); - } -}; - -app.map({ - '/users': { - get: users2.list, - del: users2.del, - '/:uid': { - get: users.get , - '/pets': { - get: pets2.list, - '/:pid': { - del: pets2.del - } - } - } - } -}); - -app.listen(3000); - -/////////////////////////// - -// Example requests: -// curl http://localhost:3000/user/0 -// curl http://localhost:3000/user/0/edit -// curl http://localhost:3000/user/1 -// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) -// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) - -function loadUser(req: express.Request, res: express.Response, next) { - // You would fetch your user from the db - var user = users[req.params.id]; - if (user) { - req.user = user; - next(); - } else { - next(new Error('Failed to load user ' + req.params.id)); - } -} - -function andRestrictToSelf(req: express.Request, res: express.Response, next) { - // If our authenticated user is the user we are viewing - // then everything is fine :) - if (req.authenticatedUser.id == req.user.id) { - next(); - } else { - // You may want to implement specific exceptions - // such as UnauthorizedError or similar so that you - // can handle these can be special-cased in an error handler - // (view ./examples/pages for this) - next(new Error('Unauthorized')); - } -} - -function andRestrictTo(role) { - return (req: express.Request, res: express.Response, next) => { - if (req.authenticatedUser.role == role) { - next(); - } else { - next(new Error('Unauthorized')); - } - }; -} - -// Middleware for faux authentication -// you would of course implement something real, -// but this illustrates how an authenticated user -// may interact with middleware - -app.use((req: express.Request, res: express.Response, next) => { - req.authenticatedUser = users[0]; - next(); -}); - -app.get('/', (req: express.Request, res: express.Response) => { - res.redirect('/user/0'); -}); - -app.get('/user/:id', loadUser, (req: express.Request, res: express.Response) => { - res.send('Viewing user ' + req.user.name); -}); - -app.get('/user/:id/edit', loadUser, andRestrictToSelf, (req: express.Request, res: express.Response) => { - res.send('Editing user ' + req.user.name); -}); - -app.del('/user/:id', loadUser, andRestrictTo('admin'), (req: express.Request, res: express.Response) => { - res.send('Deleted user ' + req.user.name); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -///////////////////////// - -app.set('view engine', 'jade'); -app.set('views', __dirname); - -// populate search - -db.sadd('ferret', 'tobi'); -db.sadd('ferret', 'loki'); -db.sadd('ferret', 'jane'); -db.sadd('cat', 'manny'); -db.sadd('cat', 'luna'); - -/** - * GET the search page. - */ - -app.get('/', (req: express.Request, res: express.Response) => { - res.render('search'); -}); - -/** - * GET search for :query. - */ - -app.get('/search/:query?', (req: express.Request, res: express.Response) => { - var query = req.params.query; - db.smembers(query, (err, vals) => { - if (err) return res.send(500); - res.send(vals); - }); -}); - -/** - * GET client javascript. Here we use sendfile() - * because serving __dirname with the static() middleware - * would also mean serving our server "index.js" and the "search.jade" - * template. - */ - -app.get('/client.js', (req: express.Request, res: express.Response) => { - res.sendfile(__dirname + '/client.js'); -}); - -app.listen(3000); -console.log('app listening on port 3000'); - -/////////////////// - -app.use(express.logger('dev')); - -// Required by session() middleware -// pass the secret for signed cookies -// (required by session()) -app.use(express.cookieParser('keyboard cat')); - -// Populates req.session -app.use(express.session()); - -app.get('/', (req: express.Request, res: express.Response) => { - var body = ''; - if (req.session.views) { - ++req.session.views; - } else { - req.session.views = 1; - body += '

First time visiting? view this page in several browsers :)

'; - } - res.send(body + '

viewed ' + req.session.views + ' times.

'); -}); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////////// - -// log requests -app.use(express.logger('dev')); - -// express on its own has no notion -// of a "file". The express.static() -// middleware checks for a file matching -// the `req.path` within the directory -// that you pass it. In this case "GET /js/app.js" -// will look for "./public/js/app.js". - -app.use(express.static(__dirname + '/public')); - -// if you wanted to "prefix" you may use -// the mounting feature of Connect, for example -// "GET /static/js/app.js" instead of "GET /js/app.js". -// The mount-path "/static" is simply removed before -// passing control to the express.static() middleware, -// thus it serves the file correctly by ignoring "/static" app.use('/static', express.static(__dirname + '/public')); -// if for some reason you want to serve files from -// several directories, you can use express.static() -// multiple times! Here we're passing "./public/css", -// this will allow "GET /style.css" instead of "GET /css/style.css": -app.use(express.static(__dirname + '/public/css')); - -// this examples does not have any routes, however -// you may `app.use(app.router)` before or after these -// static() middleware. If placed before them your routes -// will be matched BEFORE file serving takes place. If placed -// after as shown here then file serving is performed BEFORE -// any routes are hit: -app.use(app.router); - -app.listen(3000); -console.log('listening on port 3000'); -console.log('try:'); -console.log(' GET /hello.txt'); -console.log(' GET /js/app.js'); -console.log(' GET /css/style.css'); - -////////////////// - -/* -edit /etc/vhosts: - -127.0.0.1 foo.example.com -127.0.0.1 bar.example.com -127.0.0.1 example.com -*/ - -// Main app - -var main = express(); - -main.use(express.logger('dev')); - -main.get('/', (req: express.Request, res: express.Response) => { - res.send('Hello from main app!'); -}); - -main.get('/:sub', (req: express.Request, res: express.Response) => { - res.send('requsted ' + req.params.sub); -}); - -// Redirect app - -var redirect = express(); - -redirect.all('*', (req: express.Request, res: express.Response) => { - console.log(req.subdomains); - res.redirect('http://example.com:3000/' + req.subdomains[0]); -}); - -app.use(express.vhost('*.example.com', redirect)); -app.use(express.vhost('example.com', main)); - -app.listen(3000); -console.log('Express app started on port 3000'); - -//////////////////// - -// create an error with .status. we -// can then use the property in our -// custom error handler (Connect repects this prop as well) - -function merror(status, msg) { - var err = new Error(msg); - err.status = status; - return err; -} - -// if we wanted to supply more than JSON, we could -// use something similar to the content-negotiation -// example. - -// here we validate the API key, -// by mounting this middleware to /api -// meaning only paths prefixed with "/api" -// will cause this middleware to be invoked - -app.use('/api', (req, res: express.Response, next) => { - var key = req.query['api-key']; - - // key isnt present - if (!key) return next(merror(400, 'api key required')); - - // key is invalid - if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); - - // all good, store req.key for route access - req.key = key; +// simple logger +app.use(function(req, res, next){ + console.log('%s %s', req.method, req.url); next(); }); -// position our routes above the error handling middleware, -// and below our API middleware, since we want the API validation -// to take place BEFORE our routes -app.use(app.router); - -// middleware with an arity of 4 are considered -// error handling middleware. When you next(err) -// it will be passed through the defined middleware -// in order, but ONLY those with an arity of 4, ignoring -// regular middleware. -app.use((err, req, res: express.Response) => { - // whatever you want here, feel free to populate - // properties on `err` to treat it differently in here. - res.send(err.status || 500, { error: err.message }); +app.get('/', function(req, res){ + res.send('hello world'); }); -// our custom JSON 404 middleware. Since it's placed last -// it will be the last middleware called, if all others -// invoke next() and do not respond. -app.use((req: express.Request, res: express.Response) => { - res.send(404, { error: "Lame, can't find that" }); +var router = express.Router(); + +router.use((req, res, next) => { next(); }) +router.route('/users') + .get((req, res, next) => { + res.send(req.query['token']); + }); + +app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); }); -// map of valid api keys, typically mapped to -// account info with some sort of database like redis. -// api keys do _not_ serve as authentication, merely to -// track API usage or help prevent malicious behavior etc. +app.use(router); -var apiKeys = ['foo', 'bar', 'baz']; - -// these two objects will serve as our faux database - -var repos = [ - { name: 'express', url: 'http://github.com/visionmedia/express' } - , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } - , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } -]; - -var userRepos = { - tobi: [repos[0], repos[1]] - , loki: [repos[1]] - , jane: [repos[2]] -}; - -// we now can assume the api key is valid, -// and simply expose the data - -app.get('/api/users', (req: express.Request, res: express.Response) => { - res.send(users); -}); - -app.get('/api/repos', (req: express.Request, res: express.Response) => { - res.send(repos); -}); - -app.get('/api/user/:name/repos', (req: express.Request, res: express.Response, next) => { - var name = req.params.name - , user = userRepos[name]; - - if (user) res.send(user); - else next(); -}); - -if (!module.parent) { - app.listen(3000); - console.log('Express server listening on port 3000'); -} - -////// - -var router = new express.Router(); - -router.get('/', function (req, resp, next?) { - resp.send('response from router'); - resp.end(); - if (next) { - next(); - } -}); - -function test_general() { - - app.use((err, req, res: express.Response) => { - console.error(err.stack); - res.send(500, 'Something broke!'); - }); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(() => {}); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - - app.get('/', (req: express.Request, res: express.Response) => { - res.send('hello world'); - }); - - app.listen(3000); - - app.set('title', 'My Site'); - app.get('title'); - - app.enable('trust proxy'); - app.get('trust proxy'); - - app.disable('trust proxy'); - app.get('trust proxy'); - - app.enabled('trust proxy'); - - app.configure(() => { - app.set('title', 'My Application'); - }); - - app.configure('development', () => { - app.set('db uri', 'localhost/dev'); - }); - - app.configure('stage', 'production', () => {}); - - app.configure('1', '2', '3', () => {}); - - app.use((req: express.Request, res: express.Response) => { - res.send('Hello World'); - }); - - app.engine('jade', require('jade').__express); - - var User; - app.param('user', (req: express.Request, res: express.Response, next, id) => { - User.find(id, (err, user) =>{ - if (err) { - next(err); - } else if (user) { - req.user = user; - next(); - } else { - next(new Error('failed to load user')); - } - }); - }); - - app.get(/^\/commits\/(\d+)(?:\.\.(\d+))?$/, (req: express.Request, res: express.Response) => { - var from = req.params[0]; - var to = req.params[1] || 'HEAD'; - res.send('commit range ' + from + '..' + to); - }); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - - var requireAuthentication; - var loadUser = () => {}; - app.all('*', requireAuthentication, loadUser); - app.all('*', loadUser); - app.all('*', loadUser, loadUser, loadUser); - - app.locals.title = 'My App'; - app.locals.strftime = require('strftime'); - app.locals({ - title: 'My App', - phone: '1-250-858-9990', - email: 'me@myapp.com' - }); - app.render('email', () => {}); - - app.render('email', { name: 'Tobi' }, () => {}); -} - -function test_request() { - var req: express.Request; - req.params.name; - req.params[0]; - req.query.q; - req.body.user.name; - app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })); - req.param('name'); - req.route; - req.cookies.name; - req.signedCookies; - req.get('Content-Type'); - req.accepts('html'); - req.accepts(['html', 'json']); - req.is('html'); - req.ip; - req.path; - req.host; - req.fresh; - req.stale; - req.xhr; - req.protocol; - req.subdomains; - req.originalUrl; - req.acceptedLanguages; - req.acceptedCharsets; - var charset; - req.acceptsCharset(charset); - var lang; - req.acceptsLanguage(lang); - req.session = null; -} - -function test_response() { - var res: express.Response; - res.status(404).sendfile('path/to/404.png'); - res.set('Content-Type', 'text/plain'); - res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - 'ETag': '12345' - }); - res.get('Content-Type'); - res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }); - res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }); - res.cookie('cart', { items: [1, 2, 3] }); - res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });; - res.cookie('name', 'tobi', { signed: true }); - res.cookie('name', 'tobi', { path: '/admin' }); - res.clearCookie('name', { path: '/admin' }); - res.redirect('/foo/bar'); - res.redirect('http://example.com'); - res.redirect(301, 'http://example.com'); - res.charset = 'value'; - res.send('some html'); - res.send(new Buffer('whoop')); - res.send({ some: 'json' }); - res.send('some html'); - res.send(404, 'Sorry, we cannot find that!'); - res.send(500, { error: 'something blew up' }); - res.send(200); - res.set('Content-Type', 'text/html'); - res.send(new Buffer('some html')); - res.send('some html'); - res.send({ user: 'tobi' }); - res.send([1, 2, 3]); - res.json(null); - res.json({ user: 'tobi' }); - res.json(500, { error: 'message' }); - res.jsonp(null); - res.jsonp({ user: 'tobi' }); - res.jsonp(500, { error: 'message' }); - res.jsonp({ user: 'tobi' }); - res.type('application/json'); - - res.format({ - 'text/plain': () => { - res.send('hey'); - }, - 'text/html': () => { - res.send('hey'); - }, - 'application/json': () => { - res.send({ message: 'hey' }); - } - }); - - res.attachment(); - res.attachment('path/to/logo.png'); - app.get('/user/:uid/photos/:file', (req: express.Request, res: express.Response) => { - var uid = req.params.uid - , file = req.params.file; - - req.user.mayViewFilesFrom(uid, yes => { - if (yes) { - res.sendfile('/uploads/' + uid + '/' + file); - } else { - res.send(403, 'Sorry! you cant see that.'); - } - }); - }); - - res.download('/report-12345.pdf'); - res.download('/report-12345.pdf', 'report.pdf'); - res.download('/report-12345.pdf', 'report.pdf', err => { - if (err) { } else { } - }); - - res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' - }); - - app.use((req: express.Request, res: express.Response, next) => { - res.locals.user = req.user; - res.locals.authenticated = !req.user.anonymous; - next(); - }); - res.render('index', () => {}); - res.render('user', { name: 'Tobi' }, () => {}); - -} - -function test_middleware() { - app.use(express.basicAuth('username', 'password')); - app.use(express.basicAuth((user, pass) => { - return 'tj' == user && 'wahoo' == pass; - })); - app.use(express.bodyParser()); - app.use(express.json()); - app.use(express.urlencoded()); - app.use(express.multipart()); - app.use(express.logger()); - app.use(express.compress()); - app.use(express.methodOverride()); - app.use(express.bodyParser()); - app.use(express.cookieParser()); - app.use(express.cookieParser('some secret')); - app.use(express.cookieSession()); - app.use(express.directory('public')); - app.use(express.static('public')); - app.use(router.middleware); -} - -//////////////////// - -// make sure server can be shut down -var testShutdownServer = app.listen(0); -console.log('listening on port ' + testShutdownServer.address().port); -testShutdownServer.close(); +app.listen(3000); diff --git a/express/express.d.ts b/express/express.d.ts index 40be7e4ec..d5d48308f 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,9 +1,9 @@ -// Type definitions for Express 3.1 +// Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped -/* =================== USAGE =================== +/* =================== USAGE =================== import express = require('express'); var app = express(); @@ -12,11 +12,10 @@ /// - declare module Express { // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example passport.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/passport/passport.d.ts) + // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) export interface Request { } export interface Response { } export interface Application { } @@ -26,54 +25,27 @@ declare module Express { declare module "express" { import http = require('http'); - // Merged declaration, e is both a callable function and a namespace function e(): e.Express; module e { interface IRoute { path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - - /** - * Check if this route matches `path`, if so - * populate `.params`. - */ - match(path: string): boolean; + stack: any; + all(...handler: RequestHandler[]): IRoute; + get(...handler: RequestHandler[]): IRoute; + post(...handler: RequestHandler[]): IRoute; + put(...handler: RequestHandler[]): IRoute; + delete(...handler: RequestHandler[]): IRoute; + patch(...handler: RequestHandler[]): IRoute; + options(...handler: RequestHandler[]): IRoute; } - class Route implements IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - match(path: string): boolean; - - /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param method - * @param path - * @param callbacks - * @param options - */ - new (method: string, path: string, callbacks: Function[], options: any): Route; + interface IRouterMatcher { + (name: string, ...handlers: RequestHandler[]): T; + (name: RegExp, ...handlers: RequestHandler[]): T; } - interface IRouter { + interface IRouter extends RequestHandler { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -103,9 +75,9 @@ declare module "express" { * @param name * @param fn */ - param(name: string, fn: Function): T; - - param(name: string[], fn: Function): T; + param(name: string, handler: RequestParamHandler): T; + param(name: string, matcher: RegExp): T; + param(name: string, mapper: (param: any) => any): T; /** * Special-cased "all" method, applying the given route `path`, @@ -114,68 +86,25 @@ declare module "express" { * @param path * @param fn */ - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; - all(path: string, ...callbacks: Function[]): void; + route(path: string): IRoute; - get(name: string, ...handlers: RequestFunction[]): T; - - get(name: RegExp, ...handlers: RequestFunction[]): T; - - post(name: string, ...handlers: RequestFunction[]): T; - - post(name: RegExp, ...handlers: RequestFunction[]): T; - - put(name: string, ...handlers: RequestFunction[]): T; - - put(name: RegExp, ...handlers: RequestFunction[]): T; - - del(name: string, ...handlers: RequestFunction[]): T; - - del(name: RegExp, ...handlers: RequestFunction[]): T; - - patch(name: string, ...handlers: RequestFunction[]): T; - - patch(name: RegExp, ...handlers: RequestFunction[]): T; + use(...handler: RequestHandler[]): T; + use(handler: ErrorRequestHandler): T; + use(path: string, ...handler: RequestHandler[]): T; + use(path: string, handler: ErrorRequestHandler): T; } - export class Router implements IRouter { - new (options?: any): Router; + export function Router(options?: any): Router; - middleware (): any; - - param(name: string, fn: Function): Router; - - param(name: any[], fn: Function): Router; - - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string, ...handlers: RequestFunction[]): Router; - - get(name: RegExp, ...handlers: RequestFunction[]): Router; - - post(name: string, ...handlers: RequestFunction[]): Router; - - post(name: RegExp, ...handlers: RequestFunction[]): Router; - - put(name: string, ...handlers: RequestFunction[]): Router; - - put(name: RegExp, ...handlers: RequestFunction[]): Router; - - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; - - patch(name: string, ...handlers: RequestFunction[]): Router; - - patch(name: RegExp, ...handlers: RequestFunction[]): Router; - } - - interface Handler { - (req: Request, res: Response, next?: Function): void; - } + export interface Router extends IRouter {} interface CookieOptions { maxAge?: number; @@ -189,61 +118,8 @@ declare module "express" { interface Errback { (err: Error): void; } - interface Session { - /** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - touch(): Session; - - /** - * Reset `.maxAge` to `.originalMaxAge`. - */ - resetMaxAge(): Session; - - /** - * Save the session data with optional callback `fn(err)`. - */ - save(fn: Function): Session; - - /** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - */ - reload(fn: Function): Session; - - /** - * Destroy `this` session. - */ - destroy(fn: Function): Session; - - /** - * Regenerate this request's session. - */ - regenerate(fn: Function): Session; - - user: any; - - error: string; - - success: string; - - views: any; - - count: number; - } - interface Request extends http.ServerRequest, Express.Request { - session: Session; - /** * Return request header. * @@ -450,17 +326,6 @@ declare module "express" { */ ips: string[]; - /** - * Return basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - */ - auth: any; - /** * Return subdomains as an array. * @@ -509,12 +374,6 @@ declare module "express" { //cookies: { string; remember: boolean; }; cookies: any; - /** - * Used to generate an anti-CSRF token. - * Placed by the CSRF protection middleware. - */ - csrfToken(): string; - method: string; params: any; @@ -626,14 +485,18 @@ declare module "express" { * * Options: * - * - `maxAge` defaulting to 0 - * - `root` root directory for relative filenames + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. * * Examples: * - * The following example illustrates how `res.sendfile()` may + * The following example illustrates how `res.sendFile()` may * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually + * dynamic situations. The code backing `res.sendFile()` is actually * the same code, so HTTP cache support etc is identical. * * app.get('/user/:uid/photos/:file', function(req, res){ @@ -642,19 +505,35 @@ declare module "express" { * * req.user.mayViewFilesFrom(uid, function(yes){ * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); + * res.sendFile('/uploads/' + uid + '/' + file); * } else { * res.send(403, 'Sorry! you cant see that.'); * } * }); * }); + * + * @api public + */ + sendFile(path: string): void; + sendFile(path: string, options: any): void; + sendFile(path: string, fn: Errback): void; + sendFile(path: string, options: any, fn: Errback): void; + + /** + * deprecated, use sendFile instead. */ sendfile(path: string): void; - + /** + * deprecated, use sendFile instead. + */ sendfile(path: string, options: any): void; - + /** + * deprecated, use sendFile instead. + */ sendfile(path: string, fn: Errback): void; - + /** + * deprecated, use sendFile instead. + */ sendfile(path: string, options: any, fn: Errback): void; /** @@ -668,11 +547,8 @@ declare module "express" { * This method uses `res.sendfile()`. */ download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; /** @@ -782,12 +658,10 @@ declare module "express" { * * Aliased as `res.header()`. */ - set (field: any): Response; - - set (field: string, value?: string): Response; + set(field: any): Response; + set(field: string, value?: string): Response; header(field: any): Response; - header(field: string, value?: string): Response; /** @@ -823,9 +697,7 @@ declare module "express" { * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) */ cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; /** @@ -875,9 +747,7 @@ declare module "express" { * res.redirect('../login'); // /blog/post/1 -> /blog/login */ redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; /** @@ -890,9 +760,7 @@ declare module "express" { * - `cache` boolean hinting to the engine it should cache * - `filename` filename of the view being rendered */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - render(view: string, callback?: (err: Error, html: string) => void ): void; locals: any; @@ -900,10 +768,20 @@ declare module "express" { charset: string; } - interface RequestFunction { + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: Function): any; + } + + interface RequestHandler { (req: Request, res: Response, next: Function): any; } + interface Handler extends RequestHandler {} + + interface RequestParamHandler { + (req: Request, res: Response, next: Function, param: any): any; + } + interface Application extends IRouter, Express.Application { /** * Initialize the server. @@ -919,18 +797,6 @@ declare module "express" { */ defaultConfiguration(): void; - /** - * Proxy `connect#use()` to apply settings to - * mounted applications. - **/ - use(route: string, callback?: Function): Application; - - use(route: string, server: Application): Application; - - use(callback: Function): Application; - - use(server: Application): Application; - /** * Register the given template engine callback `fn` * as `ext`. @@ -961,10 +827,6 @@ declare module "express" { */ engine(ext: string, fn: Function): Application; - param(name: string, fn: Function): Application; - - param(name: string[], fn: Function): Application; - /** * Assign `setting` to `val`, or return `setting`'s value. * @@ -977,13 +839,12 @@ declare module "express" { * @param setting * @param val */ - set (setting: string, val: string): Application; - - get(name: string): string; - - get(name: string, ...handlers: RequestFunction[]): Application; - - get(name: RegExp, ...handlers: RequestFunction[]): Application; + set(setting: string, val: string): Application; + get: { + (name: string): string; // Getter + (name: string, ...handlers: RequestHandler[]): Application; + (name: RegExp, ...handlers: RequestHandler[]): Application; + }; /** * Return the app's absolute pathname @@ -1079,18 +940,12 @@ declare module "express" { * @param env * @param fn */ - configure(env: string, fn: Function): Application; - - configure(env0: string, env1: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - configure(fn: Function): Application; - + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; /** * Render the given view `name` name with `options` @@ -1108,7 +963,6 @@ declare module "express" { * @param fn */ render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; @@ -1130,16 +984,12 @@ declare module "express" { * https.createServer({ ... }, app).listen(443); */ listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - route: IRoute; + route(path: string): IRoute; router: string; @@ -1189,237 +1039,6 @@ declare module "express" { response: Response; } - /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - function bodyParser(options?: any): Handler; - - /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - function errorHandler(opts?: any): Handler; - - /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - function methodOverride(key?: string): Handler; - - /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - function cookieParser(secret?: string): Handler; - - /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + sess.views + '

'); - * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param options - */ - function session(options?: any): Handler; - - /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - function hash(sess: string): string; - /** * Static: * @@ -1444,389 +1063,8 @@ declare module "express" { * @param root * @param options */ - function static(root: string, options?: any): Handler; - - /** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param callback or username - * @param realm - */ - export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; - - export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; - - export function basicAuth(user: string, pass: string, realm?: string): Handler; - - /** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param options - */ - function compress(options?: any): Handler; - - /** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param options - */ - function cookieSession(options?: any): Handler; - - /** - * Anti CSRF: - * - * CSRF protection middleware. - * - * This middleware adds a `req.csrfToken()` function to make a token - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's session. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param options - */ - export function csrf(options?: {value?: Function}): Handler; - - /** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param root - * @param options - */ - function directory(root: string, options?: any): Handler; - - /** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param path - * @param options - */ - export function favicon(path?: string, options?: any): Handler; - - /** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param options - */ - function json(options?: any): Handler; - - /** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - */ - function limit(bytes: number): Handler; - - function limit(bytes: string): Handler; - - /** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - */ - function logger(options: string): Handler; - - function logger(options: Function): Handler; - - function logger(options?: any): Handler; - - /** - * Compile `fmt` into a function. - * - * @param fmt - */ - function compile(fmt: string): Handler; - - /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - function token(name: string, fn: Function): any; - - /** - * Define a `fmt` with the given `name`. - */ - function format(name: string, str: string): any; - - function format(name: string, str: Function): any; - - /** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - */ - function query(options: any): Handler; - - /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - function responseTime(): Handler; - - /** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - */ - function staticCache(options: any): Handler; - - /** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - */ - function timeout(ms: number): Handler; - - /** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param hostname - * @param server - */ - function vhost(hostname: string, server: any): Handler; - - function urlencoded(): any; - - function multipart(): any; - + function static(root: string, options?: any): RequestHandler; } export = e; } - diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index eec70c8f6..d532b1c56 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -324,7 +324,7 @@ declare module fabric { setWidth(value: number): IObject; // methods - bringForward(): IObject; + bringForward(intersecting?: boolean): IObject; bringToFront(): IObject; center(): IObject; centerH(): IObject; @@ -335,6 +335,7 @@ declare module fabric { drawBorders(context: CanvasRenderingContext2D): IObject; drawCorners(context: CanvasRenderingContext2D): IObject; get (property: string): any; + getBoundingRect(): {left:number; top:number; width:number; height:number}; getBoundingRectHeight(): number; getBoundingRectWidth(): number; getSvgStyles(): string; @@ -354,7 +355,7 @@ declare module fabric { scale(value: number): IObject; scaleToHeight(value: number): IObject; scaleToWidth(value: number): IObject; - sendBackwards(): IObject; + sendBackwards(intersecting?: boolean): IObject; sendToBack(): IObject; set (properties: IObjectOptions): IObject; diff --git a/fingerprintjs/fingerprint-tests.ts b/fingerprintjs/fingerprint-tests.ts new file mode 100644 index 000000000..8b0789870 --- /dev/null +++ b/fingerprintjs/fingerprint-tests.ts @@ -0,0 +1,53 @@ +/// + +function test_no_option() { + var fingerprint = new Fingerprint().get(); +} + +function test_set_canvas_enabled() { + var fingerprint = new Fingerprint({canvas: true}).get(); +} + +function test_set_screen_resolution_enabled() { + var fingerprint = new Fingerprint({screen_resolution: true}).get(); +} + +function test_set_ie_activex_enabled() { + var fingerprint = new Fingerprint({ie_activex: true}).get(); +} + +function test_set_hasher_in_option() { + var my_hasher = (value: string, seed: number) => { return value.length % seed; }; + var fingerprint = new Fingerprint({hasher: my_hasher}).get(); + + var fingerprint = new Fingerprint({hasher: (value, seed) => { return value.length % seed; }}).get(); +} + +function test_set_hasher_in_constructor() { + var my_hasher = (value: string, seed: number) => { return value.length % seed; }; + var fingerprint = new Fingerprint(my_hasher).get(); + + var fingerprint = new Fingerprint((value, seed) => { return value.length % seed; }).get(); +} + +function test_call_methods() { + var f = new Fingerprint(); + f.murmurhash3_32_gc("abcde", 123); + if (f.hasLocalStorage()) { + alert("LocalStorage"); + } + if (f.hasSessionStorage()) { + alert("SessionStorage"); + } + if (f.isCanvasSupported()) { + alert("CanvasSupported"); + } + if (f.isIE()) { + alert("IE"); + } + f.getPluginsString(); + f.getRegularPluginsString(); + f.getIEPluginsString(); + f.getScreenResolution(); + f.getCanvasFingerprint(); +} diff --git a/fingerprintjs/fingerprint.d.ts b/fingerprintjs/fingerprint.d.ts new file mode 100644 index 000000000..f472b0489 --- /dev/null +++ b/fingerprintjs/fingerprint.d.ts @@ -0,0 +1,99 @@ +// Type definitions for fingerprintjs 0.5.4 +// Project: https://github.com/Valve/fingerprintjs +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module FingerprintJs { + + interface FingerprintStatic { + /** + * Create Fingerprint object. + */ + new(hasher: (key: string, seed: number) => number): Fingerprint; + new(option: FingerprintOption): Fingerprint; + new(): Fingerprint; + } + + interface Fingerprint { + /** + * Generate fingerprint number. + */ + get(): number; + + /** + * Generate fingerprint number using Murmur hashing. + * @param key ASCII only + * @param seed Positive integer only + */ + murmurhash3_32_gc(key: string, seed: number): number; + + /** + * Check whether or not the browser has local storage. + */ + hasLocalStorage(): boolean; + + /** + * Check whether or not the browser has session storage. + */ + hasSessionStorage(): boolean; + + /** + * Check whether or not the browser supports canvas. + */ + isCanvasSupported(): boolean; + + /** + * Check whether or not the browser is IE. + */ + isIE(): boolean; + + /** + * Get plugins string. + */ + getPluginsString(): string; + + /** + * Get plugins string from navigator plugins. + */ + getRegularPluginsString(): string; + + /** + * Get plugins string from ActiveXObject. + */ + getIEPluginsString(): string; + + /** + * Get screen height and width. + */ + getScreenResolution(): number[]; + + /** + * Get canvas data url string. + */ + getCanvasFingerprint(): string; + } + + interface FingerprintOption { + /** + * If you want to use canvas fingerprinting, set true. + */ + canvas?: boolean; + + /** + * If you want to use the screen resolution in calculating the fingerprint, set true. + */ + screen_resolution?: boolean; + + /** + * If you want to query the IE plugins info to further diversify the fingerprinting process, set true. + */ + ie_activex?: boolean; + + /** + * If you want to use custom hashing function, set function. + */ + hasher?: (key: string, seed: number) => number; + } +} + +declare var Fingerprint: FingerprintJs.FingerprintStatic; diff --git a/gapi/gapi.d.ts b/gapi/gapi.d.ts index 8a9206663..d9d6fb90b 100644 --- a/gapi/gapi.d.ts +++ b/gapi/gapi.d.ts @@ -141,6 +141,23 @@ declare module gapi.client { statusText: string; } ) => any):void; + /** + * HttpRequest supports promises. + */ + then(success:(response:{ + result:T; + body:string; + headers?: any[]; + status?: number; + statusText?: string + })=>void, + failure:(response:{ + result:T; + body:string; + headers?: any[]; + status?: number; + statusText?: string + })=>void): void; } /** * Represents an HTTP Batch operation. Individual HTTP requests are added with the add method and the batch is executed using execute. diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 0bdaeb4bf..4510e38cb 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -91,6 +91,7 @@ interface GlobalizeCulture { isRTL: boolean; language: string; numberFormat: GlobalizeNumberFormat; + calendar: GlobalizeCalendar; calendars: GlobalizeCalendars; messages: any; } diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 11a1f780c..2657d8274 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -58,7 +58,7 @@ declare module google { setRefreshInterval(interval: number): void; setOption(key: string, value: any): void; setOptions(options: Object): void; - setView(view_spec: DataView): void; + setView(view_spec: string): void; } //#endregion @@ -71,17 +71,68 @@ declare module google { addColumn(descriptionObject: DataTableColumnDescription): number; addRow(cellObject: DataObjectCell): number; addRow(cellArray?: any[]): number; - addRows(count: number): number; - addRows(array: DataObjectCell[][]): number; - addRows(array: any[]): number; + addRows(numberOfEmptyRows: number): number; + addRows(rows: DataObjectCell[][]): number; + addRows(rows: any[][]): number; + clone(): DataTable; + getColumnId(columnIndex: number): String; + getColumnLabel(columnIndex: number): string; + getColumnPattern(columnIndex: number): string; + getColumnProperties(columnIndex: number): Properties; + getColumnProperty(columnIndex: number, name: string): any; + getColumnRange(columnIndex: number): { min: any; max: any }; + getColumnRole(columnIndex: string): string; + getColumnType(columnIndex: number): string; + getDistinctValues(columnIndex: number): any[]; getFilteredRows(filters: DataTableCellFilter[]): number[]; getFormattedValue(rowIndex: number, columnIndex: number): string; - getValue(rowIndex: number, columnIndex: number): any; getNumberOfColumns(): number; getNumberOfRows(): number; + getProperty(rowIndex: number, columnIndex: number, name: string): any; + getProperties(rowIndex: number, columnIndex: number): Properties; + getRowProperties(rowIndex: number): Properties; + getRowProperty(rowIndex: number, name: string): Properties; + getSortedRows(sortColumn: number): number[]; + getSortedRows(sortColumn: SortByColumn): number[]; + getSortedRows(sortColumns: number[]): number[]; + getSortedRows(sortColumns: SortByColumn[]): number[]; + getTableProperties(): Properties; + getTableProperty(name: string): any; + getValue(rowIndex: number, columnIndex: number): any; + insertColumn(columnIndex: number, type: string, label?: string, id?: string): void; + insertRows(rowIndex: number, numberOfEmptyRows: number): void; + insertRows(rowIndex: number, rows: DataObjectCell[][]): void; + insertRows(rowIndex: number, rows: any[][]): void; + removeColumn(columnIndex: number): void; + removeColumns(columnIndex: number, numberOfColumns: number): void; removeRow(rowIndex: number): void; removeRows(rowIndex: number, numberOfRows: number): void; + setCell(rowIndex: number, columnIndex: number, value?: any, formattedValue?: string, properties?: Properties): void; setColumnLabel(columnIndex: number, label: string): void; + setColumnProperty(columnIndex: number, name: string, value: any): void; + setColumnProperties(columnIndex: number, properties: Properties): void; + setFormattedValue(rowIndex: number, columnIndex: number, formattedValue: string): void; + setProperty(rowIndex: number, columnIndex: number, name: string, value: any): void; + setProperties(rowIndex: number, columnIndex: number, properties: Properties): void; + setRowProperty(rowIndex: number, name: string, value: any): void; + setRowProperties(rowIndex: number, properties: Properties): void; + setTableProperty(name: string, value: any): void; + setTableProperties(properties: Properties): void; + setValue(rowIndex: number, columnIndex: number, value: any): void; + sort(sortColumn: number): number[]; + sort(sortColumn: SortByColumn): number[]; + sort(sortColumns: number[]): number[]; + sort(sortColumns: SortByColumn[]): number[]; + toJSON(): string; + } + + export interface Properties { + [property: string]: any + } + + export interface SortByColumn { + column: number; + desc: boolean; } export interface DataTableColumnDescription { @@ -113,6 +164,9 @@ declare module google { export interface DataTableCellFilter { column: number; + value?: any; + minValue?: any; + maxValue?: any; } export interface DataObjectCell { @@ -139,7 +193,56 @@ declare module google { export class DataView { constructor(data: DataTable); constructor(data: DataView); + + getColumnId(columnIndex: number): String; + getColumnLabel(columnIndex: number): string; + getColumnPattern(columnIndex: number): string; + getColumnProperty(columnIndex: number, name: string): any; + getColumnRange(columnIndex: number): { min: any; max: any }; + getColumnType(columnIndex: number): string; + getDistinctValues(columnIndex: number): any[]; + getFilteredRows(filters: DataTableCellFilter[]): number[]; + getFormattedValue(rowIndex: number, columnIndex: number): string; + getNumberOfColumns(): number; + getNumberOfRows(): number; + getProperty(rowIndex: number, columnIndex: number, name: string): any; + getProperties(rowIndex: number, columnIndex: number): Properties; + getRowProperty(rowIndex: number, name: string): Properties; + getSortedRows(sortColumn: number): number[]; + getSortedRows(sortColumn: SortByColumn): number[]; + getSortedRows(sortColumns: number[]): number[]; + getSortedRows(sortColumns: SortByColumn[]): number[]; + getTableProperty(name: string): any; + getValue(rowIndex: number, columnIndex: number): any; + getTableColumnIndex(viewColumnIndex: number): number; + getTableRowIndex(viewRowIndex: number): number; + getViewColumnIndex(tableColumnIndex: number): number; + getViewColumns(): number[]; + getViewRowIndex(tableRowIndex: number): number; + getViewRows(): number[]; + + hideColumns(columnIndexes: number[]): void; + hideRows(min: number, max: number): void; + hideRows(rowIndexes: number[]): void; + + setColumns(columnIndexes: number[]): void; + setColumns(columnIndexes: ColumnSpec[]): void; setColumns(columnIndexes: any[]): void; + setRows(min: number, max: number): void; + setRows(rowIndexes: number[]): void; + + toDataTable(): DataTable; + toJSON(): string; + } + + export interface ColumnSpec { + calc: (dataTable: DataTable, row: number) => any; + type: string; + label?: string; + id?: string; + sourceColumn?: number; + properties?: Properties; + role?: string; } //#endregion @@ -244,10 +347,10 @@ declare module google { } export interface ChartArea { - top: any; - left: any; - width: any; - height: any; + top?: any; + left?: any; + width?: any; + height?: any; } export interface ChartLegend { diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index 4cf521e15..42fa6aa85 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -7,7 +7,7 @@ // Version 1.1 (TypeScript 0.9) interface IDispatcher { - addEventListener(type:string, callback:Function, scope:Object, useParam:boolean, priority:number):void; + addEventListener(type:string, callback:Function, scope?:Object, useParam?:boolean, priority?:number):void; removeEventListener(type:string, callback:Function):void; } diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index 853cac370..6b8607329 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -73,3 +73,46 @@ exports = (grunt: IGrunt) => { fileMaps[0].src.length; fileMaps[0].dest; }; + +// Official grunt task template from +// https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js +exports.exports = function(grunt: IGrunt) { + + // Please see the Grunt documentation for more information regarding task + // creation: http://gruntjs.com/creating-tasks + + grunt.registerMultiTask('taskName', 'task description', function() { + // Merge task-specific and/or target-specific options with these defaults. + var options = this.options({ + punctuation: '.', + separator: ', ' + }); + + // Iterate over all specified file groups. + this.files.forEach(function(f: grunt.file.IFilesConfig) { + // Concat specified files. + var src = f.src.filter(function(filepath: string) { + // Warn on and remove invalid source files (if nonull was set). + if (!grunt.file.exists(filepath)) { + grunt.log.warn('Source file "' + filepath + '" not found.'); + return false; + } else { + return true; + } + }).map(function(filepath) { + // Read file source. + return grunt.file.read(filepath); + }).join(grunt.util.normalizelf(options.separator)); + + // Handle options. + src += options.punctuation; + + // Write the destination file. + grunt.file.write(f.dest, src); + + // Print a success message. + grunt.log.writeln('File "' + f.dest + '" created.'); + }); + }); + +}; \ No newline at end of file diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index 86923c56e..8efa08ef6 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -690,6 +690,11 @@ declare module grunt { * Log a list of obj properties (good for debugging flags). */ writeflags(obj: any): T + + /** + * Log an warning with grunt.log.warn + */ + warn(msg: string): T } /** diff --git a/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index ee3098ec4..56cce331f 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -37,9 +37,13 @@ interface HandlebarsStatic extends HandlebarsCommon { compile(input: any, options?: any): HandlebarsTemplateDelegate; } -interface HandlebarsRuntimeStatic extends HandlebarsCommon { +interface HandlebarsTemplates { + [index: string]: HandlebarsTemplateDelegate; +} + +interface HandlebarsRuntimeStatic extends HandlebarsCommon { // Handlebars.templates is the default template namespace in precompiler. - templates: { (s: string): HandlebarsTemplateDelegate }[]; + templates: HandlebarsTemplates; } declare class SafeString { diff --git a/hashmap/hashmap-tests.ts b/hashmap/hashmap-tests.ts new file mode 100644 index 000000000..4c3d74ee0 --- /dev/null +++ b/hashmap/hashmap-tests.ts @@ -0,0 +1,24 @@ +/// + +var map : HashMap = new HashMap(); + +map.set("foo", 123); + +var value : number = map.get("foo"); + +map.has("foo"); + +map.remove("foo"); + +var keys : string[] = map.keys(); + +var values : number[] = map.values(); + +var count : number = map.count(); + +map.forEach(function(value : number, key : string) : void { + console.log(key); + console.log(value); +}); + +map.clear(); diff --git a/hashmap/hashmap.d.ts b/hashmap/hashmap.d.ts new file mode 100644 index 000000000..c9f858174 --- /dev/null +++ b/hashmap/hashmap.d.ts @@ -0,0 +1,71 @@ +// Type definitions for HashMap 1.1.0 +// Project: https://github.com/flesler/hashmap +// Definitions by: Rafał Wrzeszcz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class HashMap { + /** + * Return value from hashmap. + * + * @param key Key. + * @return Value stored under given key. + */ + get(key : KeyType) : ValueType; + + /** + * Store value in hashmap. + * + * @param key Key. + * @param value Value. + */ + set(key : KeyType, value : ValueType) : void; + + /** + * Checks if given key exists in hashmap. + * + * @param key Key. + * @return Whether given key exists in hashmap. + */ + has(key : KeyType) : boolean; + + /** + * Removes given key from hashmap. + * + * @param key Key. + */ + remove(key : KeyType) : void; + + /** + * Returns all contained keys. + * + * @return List of keys. + */ + keys() : KeyType[]; + + /** + * Returns all container values. + * + * @return List of values. + */ + values() : ValueType[]; + + /** + * Returns size of hashmap (number of entries). + * + * @return Number of entries in hashmap. + */ + count() : number; + + /** + * Clears hashmap. + */ + clear() : void; + + /** + * Iterates over hashmap. + * + * @param callback Function to be invoked for every hashmap entry. + */ + forEach(callback : (value : ValueType, key : KeyType) => void) : void; +} + diff --git a/htmlparser2/htmlparser2-tests.ts b/htmlparser2/htmlparser2-tests.ts new file mode 100644 index 000000000..53f6ee2aa --- /dev/null +++ b/htmlparser2/htmlparser2-tests.ts @@ -0,0 +1,24 @@ +/// +/** + * Created by staticfunction on 8/4/14. + */ +import htmlparser = require("htmlparser2"); + +var parser = new htmlparser.Parser({ + onopentag: (name:string, attribs:{[s:string]:string}) => { + if(name === "script" && attribs['type'] === "text/javascript"){ + console.log("JS! Hooray!"); + } + }, + ontext: (text: string) => { + console.log("-->", text); + }, + onclosetag: (tagname:string) => { + if(tagname === "script"){ + console.log("That's it?!"); + } + } +}); + +parser.write("Xyz "); +parser.end(); diff --git a/htmlparser2/htmlparser2.d.ts b/htmlparser2/htmlparser2.d.ts new file mode 100644 index 000000000..77fb0b983 --- /dev/null +++ b/htmlparser2/htmlparser2.d.ts @@ -0,0 +1,89 @@ +// Type definitions for htmlparser2 v3.7.x +// Project: https://github.com/fb55/htmlparser2/ +// Definitions by: James Roland Cabresos +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "htmlparser2" { + + export interface Handler { + onopentag?:(name:string, attribs:{[type:string]: string}) => void; + onopentagname?:(name:string) => void; + onattribute?:(name:string, value:string) => void; + ontext?:(text:string) => void; + onclosetag?: (text:string) => void; + onprocessinginstruction?:(name:string, data:string) => void; + oncomment?:(data:string) => void; + oncommentend?:() => void; + oncdatastart?:() => void; + oncdataend?:() => void; + onerror?:(error:Error) => void; + onreset?:() => void; + onend?:() => void; + } + + export interface Options { + + /*** + * Indicates whether special tags (